• Post Reply Bookmark Topic Watch Topic
  • New Topic

help with FileReader and FileWriter  RSS feed

 
Minu Jain
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in the code below when i use args[0]="minu", the for statement gives the output as "minu" and when i use the while statement the output comes "iu". what can i do to get "minu" as the output using while statement.

FileReader fileReader = null;
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter("file.txt");
char[] c = args[1].toCharArray();
for(i=0; i<c.length; i++)
{
int xyz = c[i];
fileWriter.write(xyz);
}
fileWriter.flush();
fileWriter.close();

fileReader = new FileReader("file.txt");
while(fileReader.read() != -1)
//for(i=0; i<c.length; i++)
{
System.out.println((char)fileReader.read());
}
}
catch(IOException e)
{
System.out.println("error!");
}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're calling read() twice per while loop iteration; once in the control part, and once in the loop body. So you're actually skipping every other character. To fix this, you have to call read() just once per iteration. There are several ways you might do this; often people write something like this:

 
Minu Jain
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you. i just couldnt see it. it worked!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!