Click to See Complete Forum and Search --> : Reading / Writing files
dyang
Aug 14th, 2002, 02:18 AM
Hi.
I have a question about reading and writing files.
Say if I have a file with a header I can use the readLine method to read to the end of the line but how can I add additional text from that point to the same file without overwriting it?
Daok
Aug 14th, 2002, 08:14 AM
Put in a string the text you want before. Put in a string the text you want after.
Print in the file your string1 + NEW STUFF + string2...
Dillinger4
Aug 14th, 2002, 11:34 PM
I think any additional data that you want written to the begining of the file will overwrite any existing data that you had before. You can append data to the end of a file by creating a FileOutputStream(String file, boolean append) and passing true to the second parameter.
I think that Daok has the right idea. Use the ReadLine() method found in the BufferedReader class then do some string manipulation to tag the begining with the new data.
Dillinger4
Aug 15th, 2002, 01:21 AM
As an example, if you have an existing text file and you run this code the data will be inserted into the begining of the file. I wouldn't suggest using this technique if the file contains a large amount of data as performance might be an issue.
import java.io.*;
class Insert{
public static void main(String[] args){
readData();
}
public static void readData(){
try{
StringBuffer sb = new StringBuffer();
BufferedReader buffr = new BufferedReader(new FileReader("C://Java/text.txt"));
while(true){
String s = buffr.readLine();
if(s == null) break;
sb.append(s);
}
buffr.close();
writeData(sb);
}catch(Exception e){System.err.println(e);}
}
public static void writeData(StringBuffer sb){
try{
BufferedWriter buffw = new BufferedWriter(new FileWriter("C://Java/text.txt"));
String additionaldata = new String("Additional data");
sb.insert(0,additionaldata);
buffw.write(new String(sb));
buffw.flush();
buffw.close();
}catch(Exception e){System.err.println(e);}
}
}
dyang
Aug 15th, 2002, 02:25 AM
Thanks Dilenger4 and MasterDaok I understand now and got it working.
Instead of
out = new PrintWriter(new BufferedWriter(new FileWriter(file_name)));
i just used
out = new PrintWriter(new BufferedWriter(new FileWriter(file_name, true)));
and it works perfect. :)
Dillinger4
Aug 15th, 2002, 02:32 AM
Yeah i wasnt clear on wether you were talking about appending data to the end of a file or inserting data at the begining. But that constructor comes in handy for appending. My only gripe about that is there is no constructor that takes a file object as a parameter and a boolen value indicating wether you would like to append.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.