Java - how to read from file when I used PrintWriter, BufferedWriter and FileWriter to write?

谁说我不能喝 提交于 2019-12-08 16:06:31

问题


I have method which writes some data to file. I use PrintWriter, BufferedWriter and FileWriter as shown below

public void writeToFile(String FileName){
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(new BufferedWriter(new FileWriter(FileName)));
        for(Cars car : list){
            pw.println(car.getType());
            pw.println(car.getMaxSpeed());
            pw.println(car.getOwner());
            pw.println();
            pw.flush();
        }
        pw.close();
    }
    catch(IOException ex){
        System.err.println(ex);
    }
}

Now how can I read this data from file? I tried to use InputStreamReader, BufferedReader and FileInputStream, but my NetBeans shows me an error message

    public void readFromFile() throws IOException {
        InputStreamReader fr = null;
        try {
            fr = new InputStreamReader(new BufferedReader(new FileInputStream(new FileReader("c:\\cars.txt"))));
            System.out.println(fr.read());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        } finally {
            fr.close();
        }
    }  

What is wrong with this method?


回答1:


BufferedReader in = new BufferedReader(new FileReader("file.in"));
BufferedWriter out = new BufferedWriter(new FileWriter("file.out"));

String line = in.readLine(); // <-- read whole line
StringTokenizer tk = new StringTokenizer(line);
int a = Integer.parseInt(tk.nextToken()); // <-- read single word on line and parse to int

out.write(""+a);
out.flush();



回答2:


There are several problems in your code :

1) An InputStreamReader takes an InputStream as an argument not a Reader. See http://docs.oracle.com/javase/6/docs/api/java/io/InputStreamReader.html.

2) The FileInputStream does not accept a Reader as argument as well (it takes a File, a FileDescriptor, or a String). See : http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html

3) A BufferedReader reads the File line by line normally. The read() method only reads a single character.

A possible solution could be :

fr = new BufferedReader(new InputStreamReader(new FileInputStream(new File("c:\\cars.txt"))));
String line = "";
while((line = fr.readLine()) != null) {
    System.out.println(line);
}

Btw : It would be easier for others to help you, if you provide the exact error-message or even better the StackTrace.




回答3:


Simple error: Cannot resolve constructor 'FileInputStream(java.io.FileReader)', required constructor not exist in API.

Your original code was:

new PrintWriter(new BufferedWriter(new FileWriter(FileName)));

so for reading, you need

new PrintReader(new BufferedReader(new FileReader(FileName)));

but PrintReader is not needed (not exist), so all you need is:

new BufferedReader(new FileReader(FileName))

PrinterWriter prints formatted representations of objects to a text-output stream, but when reading text is always formatted, so PrinterReader not exist.

You are writing line by line, so also read line by line :) Example:

public void readFromFile() throws IOException {
    BufferedReader bufferedReader = null;
    try {
        String sCurrentLine;
        bufferedReader = new BufferedReader(new FileReader("c:\\cars.txt"));
        while ((sCurrentLine = bufferedReader.readLine()) != null) {
            System.out.println(sCurrentLine);
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    } finally {
        bufferedReader.close();
    }
}

or better (JDK7)

void readFromFile() throws IOException {
    Path path = Paths.get("c:\\cars.txt");
    try (BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset())){
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

    }
}


来源:https://stackoverflow.com/questions/16135726/java-how-to-read-from-file-when-i-used-printwriter-bufferedwriter-and-filewri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!