对文件写0操作时的陷阱
来源:互联网 发布:eliza 人工智能 编辑:程序博客网 时间:2024/06/06 14:02
之前在实际开发过程中,需要对文件做写0操作,防止文件被恢复。在向文件写0的过程中一个要素就是需要获取写0之前的文件的长度。
大概思路如下:
File file = new File("H:\\tmp\\test.txt"); FileOutputStream oStream = new FileOutputStream(file);for(int i = 0; i < file.length(); i++){ oStream.write(0);}
这里其实犯了一个错误,此时获取到的file.lenght为0;
实测代码如下:
public void test() throws FileNotFoundException { File file = new File("H:\\tmp\\test.txt"); System.out.println(file.length()); FileOutputStream oStream = new FileOutputStream(file); System.out.println(file.length());}
打印结果如下:
100
出现该问题的原因是在使用FileOutpuStream的时候创建了一个新的文件对象,原来的数据被清空了。可以从如下代码进一步验证:
public void test2() throws FileNotFoundException { File file = new File("H:\\tmp\\test.txt"); System.out.println(file.length()); FileOutputStream oStream = new FileOutputStream(file,true); System.out.println(file.length());}
打印结果如下:
1010
在使用FileOutputStream(Filefile, boolean append) 方法实例化文件输出流的时候采用的是追加方式,所以此时能正常的获取到文件的长度。
因此正确思路应该如下:
public void test3() throws IOException { File file = new File("H:\\tmp\\test.txt"); long fileLength = file.length(); try (FileOutputStream oStream = new FileOutputStream(file)) { System.out.println(fileLength); for (int i = 0; i < fileLength; i++) { oStream.write(0); } } catch (Exception e) { System.out.println(e); }}
这种写法还可以减少循环计算file.length的次数。如果编译器有优化则要另说了。
0 0
- 对文件写0操作时的陷阱
- java 对properties 文件的写操作
- sed对文件的写操作
- 对HDFS文件系统文件的读、写、删操作
- 对HDFS文件系统文件的读、写、删操作
- jxl包实现对Excel文件的写读写操作
- 对HDFS文件系统文件的读、写、删操作 .
- IO操作 对已有文件的数据续写
- 简单的对文件操作,如复制,读,写
- 文件的写操作
- 对服务器端文件进行写操作
- 对文件的操作
- 对文件的操作
- 对文件的操作
- 对文件的操作
- 对文件的操作
- 对文件的操作
- 对文件的操作
- JavaWeb学习(三):jsp
- 算法排序 归并 理解性写
- 202. Happy Number
- 算法 小端排序
- leetcode 6. ZigZag Conversion
- 对文件写0操作时的陷阱
- ios oc之block
- 算法学习之路
- git使用
- 机器学习 - 概念学习
- C++模板板块
- Python学习笔记(三)
- MyVector
- ios开发之抽屉效果图