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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With