java怎样向TXT中写入程序,然后保存,然后可以继续写入,不会覆盖原有记录,写一下这部分的代码

谢谢大家,比较急
2024-11-23 21:35:11
推荐回答(2个)
回答1:

package test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
BufferedReader br = null;
File f = null;
FileWriter fw = null;
BufferedWriter bw = null;
try {
f = new File("C:/test.log");
fw = new FileWriter(f,true);
bw = new BufferedWriter(fw);
for(;;){
System.out.println("please input your message:(exit to quit");
br=new BufferedReader(new InputStreamReader(System.in));
String a = br.readLine();
if("exit".equalsIgnoreCase(a)) break;
bw.write(a);
bw.flush();
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
bw.close();
fw.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}
}

回答2:

FileOutputStream(String name, boolean append)
Creates an output file stream to write to the file with the specified name.