Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

methods

file

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?

like image 203
marek Avatar asked Apr 21 '13 20:04

marek


1 Answers

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.

like image 163
Don Avatar answered Oct 18 '22 02:10

Don