Java - how to read from file when I used PrintWriter, BufferedWriter and FileWriter to write?
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();
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.