【问题标题】:data being written to file is not appearing写入文件的数据未出现
【发布时间】:2015-11-05 15:28:42
【问题描述】:

在按下按钮时的其中一项活动中,我想在外部存储上创建一个文件。所以我写了 下面的代码可以做到这一点。

但最终文件被创建但为空..为什么?

代码

public void tx(byte[] data) {
    Log.w(TAG, CSubTag.bullet("tx"));

    File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
    try {
        file.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        OutputStream os = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(os);
        try {
            bos.write("data_stream".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • 'file.createNewFile();'。删除它。那个完整的 try-catch 块。它没有任何作用。

标签: java android outputstream fileoutputstream


【解决方案1】:

请关闭 finally 块中的 OutputStream 和 BufferedOutputStream。否则,数据将不会被写入。

【讨论】:

    猜你喜欢
    • 2015-07-21
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 2022-01-04
    • 1970-01-01
    • 2020-09-16
    相关资源
    最近更新 更多