• Post Reply Bookmark Topic Watch Topic
  • New Topic

Writing String to a Text file

 
Prabha Dhandapani
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Donny Nadolny
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
roy joseph
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the Streams and I/O forum...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!