• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

FileWriter, File Created but no content

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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".
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic