Hello everybody, I want to write a string to a text file and my code is as follows:
I need to write the name of a file into a text file called totalfilelist.txt. Also, I need to append the names of all the files from the path. Can somebody help me with this...It is very very urgent...Looking for Ranchers help! Many Thanks in Advance, Prabha
Hey. The problem is that when you open a file to write to, it will erase the contents of that file and overwrite it with whatever text you want. Try instead to create a string (or StringBuffer if you want it more optimized) and instead of writing the file each time (subsequently overwriting each file name you write), just append the name of the file to a string (followed by the newline character, \n, of course). Then, write that text to the file containing all the file names. Hope this helps.
- Donny Nadolny<br />The pen is mightier than the sword, and considerably easier to write with.
Alternately, you can supply "true" as a second argument to the FileWriter constructor, to specify that the file should be opened in "append" mode. But opening the file for each line of text, rather than opening it once and just printing the lines to it, is inefficient and needlessly verbose; this whole thing could be condensed into a single routine of about 6 lines.
what's the purpose for this program? if you just want the file list save to a text file, you can do that with dos commands. or you could do it in java without having to resort to filewriting code. exmple. make a class [ReadFileList.class] that reads a directory and then print filenames using System.out.println statements. then run the program like this. java ReadFileList > FileList.txt