正在写入文件的数据没有出现

时间:2022-12-19 20:22:36

in one of the activities when a button is pressed i want to create a file on the extran storage. so i wrote the below code to do so.

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

but in the end the file is created but empty..why?

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

code:

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();
    }
}

1 个解决方案

#1


1  

Please close the OutputStream and BufferedOutputStream inside finally block. Otherwise, the data will not be written.

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

#1


1  

Please close the OutputStream and BufferedOutputStream inside finally block. Otherwise, the data will not be written.

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