Java写文件覆盖和不覆盖原内容

将ByteBuffer转为byte[]写入文件:
写文件覆盖原内容:
            data.flip();   //data是ByteBuffer对象
            byte []sampleData = new byte[size];
            data.get(sampleData);
            String path = "/sdcard/Download/merge_out.txt";
            try {
                FileOutputStream outputStream  = new FileOutputStream(new File(path));
                outputStream.write(sampleData);
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
写文件不覆盖原内容
            data.flip();   //data是ByteBuffer对象
            byte []sampleData = new byte[size];
            data.get(sampleData);
            String path = "/sdcard/Download/merge_out.txt";
            try {
                FileOutputStream outputStream  = new FileOutputStream(new File(path),true);
                outputStream.write(sampleData);
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

注意: 区别在于

FileOutputStream outputStream  = new FileOutputStream(new File(path),true);

public FileOutputStream(File file, boolean append),当append是true时,不覆盖原内容;如果只传file一个参数,默认append是false,即覆盖原内容。

你可能感兴趣的:(Java写文件覆盖和不覆盖原内容)