在Eclipse中找不到File I / O的指定文本文件

时间:2016-03-16 10:38:14

标签: java file-io

我正在尝试在eclipse中执行文件I / O.这是代码:

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;

public class TextDB {
    public static final String SEPARATOR = "|";

    // an example of reading
    public static ArrayList readProfessors(String filename) throws IOException {
        // read String from text file
        ArrayList stringArray = (ArrayList) read(filename);
        ArrayList alr = new ArrayList();// to store Professors data

        for (int i = 0; i < stringArray.size(); i++) {
            String st = (String) stringArray.get(i);
            // get individual 'fields' of the string separated by SEPARATOR
            StringTokenizer star = new StringTokenizer(st, SEPARATOR);        // pass in the string to the string tokenizer using delimiter ","

            String name = star.nextToken().trim();        // first token
            String email = star.nextToken().trim();        // second token
            int contact = Integer.parseInt(star.nextToken().trim()); // third token
            // create Professor object from file data
            Professor prof = new Professor(name, email, contact);
            // add to Professors list
            alr.add(prof);
        }
        return alr;
    }

    // an example of saving
    public static void saveProfessors(String filename, List al) throws IOException {
        List alw = new ArrayList();// to store Professors data

        for (int i = 0; i < al.size(); i++) {
            Professor prof = (Professor) al.get(i);
            StringBuilder st = new StringBuilder();
            st.append(prof.getName().trim());
            st.append(SEPARATOR);
            st.append(prof.getEmail().trim());
            st.append(SEPARATOR);
            st.append(prof.getContact());
            alw.add(st.toString());
        }
        write(filename, alw);
    }

    /**
     * Write fixed content to the given file.
     */
    public static void write(String fileName, List data) throws IOException {
        PrintWriter out = new PrintWriter(new FileWriter(fileName));

        try {
            for (int i = 0; i < data.size(); i++) {
                out.println((String) data.get(i));
            }
        } finally {
            out.close();
        }
    }

    /**
     * Read the contents of the given file.
     */
    public static List read(String fileName) throws IOException {
        List data = new ArrayList();
        Scanner scanner = new Scanner(new FileInputStream(fileName));
        try {
            while (scanner.hasNextLine()) {
                data.add(scanner.nextLine());
            }
        } finally {
            scanner.close();
        }
        return data;
    }

    public static void main(String[] aArgs) {
        TextDB txtDB = new TextDB();
        String filename = "professor.txt";
        try {
            // read file containing Professor records.
            ArrayList al = TextDB.readProfessors(filename);
            for (int i = 0; i < al.size(); i++) {
                Professor prof = (Professor) al.get(i);
                System.out.println("Name " + prof.getName());
                System.out.println("Contact " + prof.getContact());
            }
            Professor p1 = new Professor("Joseph", "jos@ntu.edu.sg", 67909999);
            // al is an array list containing Professor objs
            al.add(p1);
            // write Professor record/s to file.
            TextDB.saveProfessors(filename, al);
        } catch (IOException e) {
            System.out.println("IOException > " + e.getMessage());
        }
    }
}

我的教授班:

import java.io.Serializable;

public class Professor implements Serializable {
    private String name;
    private String email;
    private int contact;

    public Professor(String n, String e, int c) {
        name = n;
        email = e;
        contact = c;
    }

    public String getName() {
        return name;
    }

    public int getContact() {
        return contact;
    }

    public String getEmail() {
        return email;
    }

    public boolean equals(Object o) {
        if (o instanceof Professor) {
            Professor p = (Professor) o;
            return (getName().equals(p.getName()));
        }
        return false;
    }
}

然而,当我运行它时,编译器告诉指定的文件&#34; professor.txt&#34;找不到。我以为编译器会根据这些代码自动创建文本文件吗?

提前致谢。

2 个答案:

答案 0 :(得分:0)

在你的主要文件中,你首先阅读文件,然后编写它:如果文件不存在,它会抛出异常。也许,第一次运行它时,文件就存在了(也许你已经编写了代码来编写文件,然后你就启动它了。)

所以,两个解决方案......

首先:改变你的主要顺序。

def add_or_update_score(name, class_group, score):
   with lite.connect('results.db') as conn:
      # Create the table, if doesn't exist yet
      conn.execute('CREATE TABLE IF NOT EXISTS scores (name TEXT, class_group INTEGER, score INTEGER)')
      # Check if a record already exists
      if list(conn.execute('SELECT * FROM scores where name = ?', (name,))):
         # A record already exists
         conn.execute('UPDATE scores SET score = ? WHERE (name = ? AND class_group = ?)', (score, name, class_group))
      else:
         # No record exists
        conn.execute('INSERT INTO scores VALUES (?, ?, ?)', (name, class_group, score))

第二步:检查文件是否存在,如果不存在则跳过读取

public static void main(String[] aArgs) {
    TextDB txtDB = new TextDB();
    String filename = "professor.txt";
    try {
        Professor p1 = new Professor("Joseph", "jos@ntu.edu.sg", 67909999);
        // al is an array list containing Professor objs
        al.add(p1);
        // write Professor record/s to file.
        TextDB.saveProfessors(filename, al);

        // read file containing Professor records.
        ArrayList al = TextDB.readProfessors(filename);
        for (int i = 0; i < al.size(); i++) {
            Professor prof = (Professor) al.get(i);
            System.out.println("Name " + prof.getName());
            System.out.println("Contact " + prof.getContact());
        }
    } catch (IOException e) {
        System.out.println("IOException > " + e.getMessage());
    }
}

评论后更新:

public static void main(String[] aArgs) {
    TextDB txtDB = new TextDB();
    String filename = "professor.txt";
    try {
        //check if the file exist
        File oFile = new File(filename);
        if(oFile.exist()) {
            // read file containing Professor records.
            ArrayList al = TextDB.readProfessors(filename);
            for (int i = 0; i < al.size(); i++) {
                Professor prof = (Professor) al.get(i);
                System.out.println("Name " + prof.getName());
                System.out.println("Contact " + prof.getContact());
            }
        }

        Professor p1 = new Professor("Joseph", "jos@ntu.edu.sg", 67909999);
        // al is an array list containing Professor objs
        al.add(p1);
        // write Professor record/s to file.
        TextDB.saveProfessors(filename, al);
    } catch (IOException e) {
        System.out.println("IOException > " + e.getMessage());
    }
}

答案 1 :(得分:0)

在尝试阅读应用程序中的文件之前,如果它不存在,请直接创建:

String filename = "professor.txt" ;
File file = new File(fileName);

if(!file.exists()){
  file.createNewFile();
}

或致电您的write方法。

String filename = "professor.txt" ;
File file = new File(fileName);

if(!file.exists()){
  TextDB.saveProfessors(filename, new ArrayList());
}

PrintWriter将为您创建文件,即使没有写入任何内容(例如此空列表)。