用java中的io流写入文件如何避免覆盖原来的内容?求代码

2025-01-08 00:06:51
推荐回答(3个)
回答1:

用这个方法public FileOutputStream(String name,boolean append)throws FileNotFoundException,将逻辑值append设为false时,写入的字节数据覆盖文本原来的内容,为ture是即追加到原来文本的末尾。覆盖原文本内容如:FileOutputStream x=new FileOutputStream("文件全路径",false);throws FileNotFoundException为抛出异常。

回答2:

FileWriter fileWriter = new FileWriter(fileName, true);

回答3:

public static void main(String[] args) {
// TODO Auto-generated method stub
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream("c:\\1.txt",false));
BufferedWriter bw = new BufferedWriter(osw);

String s = null;
s = br.readLine();
while (s != null) {
bw.write(s);
bw.newLine();

/**
* 添加的代码
*/
bw.flush();

System.out.println(s.toUpperCase());
s = br.readLine();
}
br.close();
bw.close();
} catch (IOException e) { }

}