• Post Reply Bookmark Topic Watch Topic
  • New Topic

Funny output

 
Shilong Zheng
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I used the following codes and i keep getting the funny outputs below, how do i rectify the problem?? i tried to initialise variable 'ch' to different values but still fails. Any advise???

try {
BufferedReader in = new BufferedReader(new FileReader("file"));
PrintWriter pw = new PrintWriter(new FileWriter("modifiedfile"));//
int ch;
char c;
ch = in.read();
c = (char) ch;
while (ch != -1) {
String str = ""+c;
ch = in.read();
c = (char) ch;
System.out.print(c);
pw.write(ch);
}
in.close();
pw.close();
}catch (IOException ioe) {
System.out.println("There was a problem reading the file");
}
}

Output
======
ame : James
Date : 6th July 2004?


Regards
Shilong
 
Joe Ess
Bartender
Posts: 9362
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, you should probably take a browse through the Java Tutorial - Reading and Writing chapter. Lots of good information in there for the beginner.
Second, you should realize that if you do two reads before you write something out, you will not print out the results of that first read.
Third, you should take a look at the documentation for java.io.BufferedReader. BufferedReader makes input more efficient by using an internal buffer to save slow disk access. It also has a convenient method for reading a line of text at a time. Using that method would be faster and easier than reading your data one character at a time.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!