如何在 truzip 中获取文件大小

how to get file size in truzip

我正在使用 truezip 版本 (7.7.9) 更新存档文件。 我的做法如下

File entry = new TFile(filepath);
writer = new TFileWriter(entry);
writer.append("MyString");
writer.flush();
long fileSize = entry.length(); // which always gives value as 0

出于某种目的,我需要准确的文件大小 但这总是给 0 有没有其他方法我可以得到它。

我阅读了 TFile 的文档 class\ https://truezip.java.net/apidocs/de/schlichtherle/truezip/file/TFile.html#length() 不太明白它的作用

来自FAQ

Every now and then you might want to treat an archive file like a regular file rather than a virtual directory. For example, when trying to obtain the length of the archive file in bytes. You would normally do this by calling the method File.length(). However, if the File object is an instance of the TFile class and the path has been detected to name a valid archive file, then this method would always return zero. This is because you might have changed the archive file and then it would be impossible to return a precise result until the changes have been committed to the target archive file.

看来您可以在更改文件之前先计算文件的大小,然后加上要追加的内容的大小,或者您需要写入文件然后调用 File.length()。您可以通过调用 TVFS.unmount() or TVFS.unmount(TFile)

来完成此操作

在官方页面查看这篇文章

The API should not detect an individual archive file as a virtual directory. How can I do this

看看这个

[...] However, if the File object is an instance of the TFile class and the path has been detected to name a valid archive file, then this method would always return zero. This is because you might have changed the archive file and then it would be impossible to return a precise result until the changes have been committed to the target archive file..

它也适用于 TPath

我想知道您是否可以使用 Files.size(路径) 来获得您需要的东西(在您的 TZip 更改之后和之前)

希望对您有所帮助。

如果存档文件有效,则returns0。如果出现任何问题,则会给出IOException。

如果您更改任何内容,则需要调用方法 TFile.umount() 来提交所有更改。

然后使用下面的方法获取一个没有检测到归档文件的TFile并调用它的length()方法:

TrueZIP 7.5中,你可以调用TFile.toNonArchiveFile()

// Note that the actual path may refer to anything, even a nested archive file.
TFile inner = new TFile("outer.zip/inner.zip");
TFile file = inner.toNonArchiveFile(); // convert - since TrueZIP 7.5
... // there may be some I/O here
TVFS.umount(inner); // unmount potential archive file
// Now you can safely do any I/O to $file.
long length = file.length();

你也可以用另一种方式做到:

private static TFile newNonArchiveFile(TFile file) {
    return new TFile(file.getParentFile(), file.getName(), TArchiveDetector.NULL);
}

资源Link: How can you get the size of a file in an archive using TrueZip?