• Post Reply Bookmark Topic Watch Topic
  • New Topic

files to strings

 
alleykat
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone I am very new to Java. I am trying to read a textfile in and convert it to a string or stringbuffer so I can parse it and write a result out to another file. Any ideas how to read a file in as a string would be appriciated.
 
Eric lau
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can try the class BufferReader and BufferWriter in the package java.io.There is a simply example below:
try{
java.io.File inf = new java.io.File(filename);
java.io.File outf = new java.io.File(newfilename);
java.io.FileReader in = new java.io.FileReader(inf);
java.io.FileWriter out = new java.io.FileWriter(outf);
java.io.BufferedReader reader = new java.io.BufferedReader(in);
java.io.BufferedWriter writer = new java.io.BufferedWriter(out);
String data;
while((data= reader.readLine())!=null){
writer.write(data+"\n");
}
writer.close();
}catch(Exception e){}
 
alleykat
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You Eric. That is just what I needed.
 
The_Hobo_Phoenix
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey, just joined, could ye tell me what the other side of that code 'the Buffer writer'? im trying to send info from a servlet to an applet and the from an applet to a servlet
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since you wanted to convert the file to a String, replace the output writer code:

with

And after all the writing is done, get the String:

Note that for a StringWriter there's really no benefit to wrapping a the writer with a BufferedWriter - the StringWriter has a StringBuffer inside it anyway, so it will probably be faster to just use the StringWriter directly without an extra buffer.
[ January 22, 2003: Message edited by: Jim Yingst ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!