Java中的不覆盖文件输出

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/H_Targaryen/article/details/79856166

在多线程电梯中需要将字符串输出到指定文件中,最开始只使用FileOutputStream发现每次都会将上次的文件覆盖然后重写,而使用BufferedWriter并且将file、true参数传入FileWriter中就能实现不覆盖输出到文件。

//需要导入的包
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
//文件输出
    public static void outFile(String s) {
        File file = new File("test.txt");
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(file,true));
            bw.write(s);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
展开阅读全文

FileOutputStream自动覆盖文件的问题

10-30

下面这段代码不会输出任何数据,因为在bufferedReader读取文本信息前rnFileOutputStream已经将D:\Debug.log覆盖为空文件..根本没有调用write方法..rn删除FileOutputStream后就能正常的读取...这是为什么呢rn[code=java]import java.io.BufferedReader;rnimport java.io.BufferedWriter;rnimport java.io.File;rnimport java.io.FileInputStream;rnimport java.io.FileNotFoundException;rnimport java.io.FileOutputStream;rnimport java.io.IOException;rnimport java.io.InputStreamReader;rnimport java.io.OutputStreamWriter;rnimport javax.swing.JOptionPane;rnrnpublic class _Writerrnrn /**rn * @param argsrn */rn public static void main(String[] args)rn rn File hosts = new File("D:\\Debug.log");rn FileOutputStream os = null;rn FileInputStream is = null;rn BufferedReader br = null;rn BufferedWriter bw = null;rn tryrn rn is = new FileInputStream(hosts);rn os = new FileOutputStream(hosts);rn br = new BufferedReader(new InputStreamReader(is));rn bw = new BufferedWriter(new OutputStreamWriter(os));rn String str = null;rn while ((str = br.readLine()) != null)rn rn System.out.println(str);rn rn catch (FileNotFoundException e)rn rn // TODO Auto-generated catch blockrn e.printStackTrace();rn JOptionPane.showMessageDialog(null, "hosts文件不存在!");rn catch (IOException e)rn rn // TODO Auto-generated catch blockrn e.printStackTrace();rn JOptionPane.showMessageDialog(null, "IO异常!");rn finallyrn rn tryrn rn if (os != null)rn os.close();rn if (is != null)rn is.close();rn if (br != null)rn br.close();rn if (bw != null)rn bw.close();rn catch (IOException e)rn rn // TODO Auto-generated catch blockrn e.printStackTrace();rn JOptionPane.showMessageDialog(null, "CLOSE异常!");rn rn rn rnrn[/code] 论坛

没有更多推荐了,返回首页