我想在Java领域实现以下目标:
- 打开一个非零大小的文件。
- 删除其所有内容。
将同一文件截断为给定大小(例如 38 字节......)
不知何故,如果我删除内容(有效),即使我在那之后发出截断,它也不会被执行并且文件大小保持为 0。
String fileName = "/home/me/dummy/a.1"; try { Long size = 0L; // file exists already RandomAccessFile raf = new RandomAccessFile(fileName, "rw"); // set the file pointer at 0 position raf.seek(0); // print current length size = raf.length(); System.out.println("Before deleting - fileSize = " + size); // set the file length to 0 raf.setLength(0); // print the new length System.out.println("After deleting - filesize = " + raf.length()); raf.close(); // truncating file to Size = 38 bytes FileChannel outChan = new FileOutputStream(fileName, true).getChannel(); System.out.println("Before Truncating - File size = "+outChan.size()); outChan.truncate(38); System.out.println("Aftre truncating - File size = "+outChan.size()); outChan.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
我的运算符(operator):
删除之前 - fileSize = 21
删除后 - 文件大小 = 0
截断之前 - 文件大小 = 0
截断后 - 文件大小 = 0
我尝试了多种其他选项,例如:
将文件截断为 0,然后表示 38 字节(我想要的非零值)
// truncating file to Size = 0 bytes and then to 38 bytes FileChannel outChan = new FileOutputStream(fileName, true).getChannel(); System.out.println("Before Truncating - File size = "+outChan.size()); outChan.truncate(0); outChan.truncate(38); System.out.println("Aftre truncating - File size = "+outChan.size()); outChan.close();
不起作用。文件大小保持为 0。仅尊重第一次截断。
2.将文件截断为0,关闭 channel ,再次打开 channel 并截断为38字节。
FileChannel outChan = new FileOutputStream(fileName, true).getChannel();
System.out.println("Before Truncating - File size = "+outChan.size());
outChan.truncate(0);
outChan.close();
FileChannel outChan1 = new FileOutputStream(fileName, true).getChannel();
outChan1.truncate(38);
System.out.println("Aftre truncating - File size = "+outChan1.size());
outChan.close();
不起作用。文件大小保持为 0。仅尊重第一次截断。
您输入的有关如何删除文件内容并将其截断为非零大小的信息。如果我可以只在一次打开中完成它,而不是像打开它(RandomAccessFile,然后作为 FileChannel)那样,那就太好了。
谢谢。
最佳答案
引用自FileChannel.truncate
javadocs :
If the given size is greater than or equal to the file's current size then the file is not modified.
由于您在截断之前清空了文件,因此其大小将为 0.38 > 0
,因此发出 .trucate(38)
将导致无操作。
要么截断为 38 个字节而不先截断为 0,要么截断为 0 并向其中写入 38 个字节(例如 38 个零)。
关于java - 如何在Java中删除文件内容(不是文件,需要相同的inode),然后将文件截断为特定大小(比如38字节),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27458402/