之前在实际开发过程中,需要对文件做写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());
}
打印结果如下:
10
0
出现该问题的原因是在使用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());
}
打印结果如下:
10
10
在使用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的次数。如果编译器有优化则要另说了。
3万+

被折叠的 条评论
为什么被折叠?



