Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

FileWriter, File Created but no content

 
Balaguru Janarthanan
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.*;
class FileWriterDemo{
public static void main(String arg[])throws IOException{
String source="i still love software";
char buffer[]=new char[source.length()];
source.getChars(0,source.length(),buffer,0);
FileWriter fw =new FileWriter("flie1.txt");
for(int i=0; i<buffer.length;i++){>
System.out.println(buffer[i]);
fw.write(buffer[i]);
}
}
}
I can see new file and empty, no contenet.
Any one pls. help me.
 
Seema Das
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Balguru,
The for loop is not contructed properly so the write statement is actually outside the loop.
But the truth is you don't need a for loop since Writer class has write method that takes a character array as its argument. So just use fw.write(buffer). and then you need to close the object (fw.close()) only then the array will be written to the file.
hth
Seema
 
sai challa
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Balaguru Janarthanan:
import java.io.*;
class FileWriterDemo{
public static void main(String arg[])throws IOException{
String source="i still love software";
char buffer[]=new char[source.length()];
source.getChars(0,source.length(),buffer,0);
FileWriter fw =new FileWriter("flie1.txt");
for(int i=0; i<buffer.length;i++){>
System.out.println(buffer[i]);
fw.write(buffer[i]);
}
}
}
I can see new file and empty, no contenet.
Any one pls. help me.

You can modify your for loop:
for(int i=0;i<buffer.length;i++)>
{
System.out.println(buffer[i]);
fw.write(buffer[i]);
fw.flush();
}
The flush() method ensures that any character present in the FileWriter fw is written to the file "flie1.txt".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic