我目前正在使用TrueZip向通过MultiPartFile上传到服务器的Zip文件中添加一个文件。
问题在追加一个文件时,zip变得无效。它不能再作为压缩文件打开。
代码让我们从我的上传控制器中的相关代码开始(文件是MultiPartFile):
// Get the file
File dest = null;
TFile zip = null;
try {
// Obtain the file locally, zip, and delete the old
dest = new File(request.getRealPath("") + "/datasource/uploads/" + fixedFileName);
file.transferTo(dest);
// Validate
zip = new TFile(dest);
resp = mls.validateMapLayer(zip);
// Now perform the upload and delete the temp file
FoundryUserDetails userDetails = (FoundryUserDetails) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
UserIdentity ui = userDetails.getUserIdentity();
MapLayer newLayer = new MapLayer();
// generate the prj
mls.generateProjection(resp, dest.getAbsolutePath(), projection);"generateProjection“方法是添加文件的地方:
public void generateProjection(UploadMapResponse resp, String fLoc, FoundryCRS proj) throws NoSuchAuthorityCodeException,
FactoryException, IOException {
TFile projFile = new TFile(fLoc, resp.getLayerName() + ".prj");
CoordinateReferenceSystem crs = CRS.decode(proj.getEpsg());
String wkt = crs.toWKT();
TConfig config = TConfig.push();
try {
config.setOutputPreferences(config.getOutputPreferences().set(FsOutputOption.GROW));
TFileOutputStream writer = new TFileOutputStream(projFile);
try {
writer.write(wkt.getBytes());
} finally {
writer.close();
}
} finally {
config.close();
}
}为了测试这种方法是否有效,我尝试了一个简单的主程序:
public static void main(String[] args) {
File f = new File("C:/Data/SierritaDec2011TopoContours.zip");
TFile tf = new TFile(f);
tf.listFiles();
TFile proj = new TFile(f, "test.prj");
TConfig config = TConfig.push();
try {
config.setOutputPreferences(config.getOutputPreferences().set(FsOutputOption.GROW));
TFileOutputStream writer = null;
try {
writer = new TFileOutputStream(proj);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
writer.write("Hello Zip world".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} finally {
// Pop the current configuration off the inheritable thread local
// stack.
config.close();
}
}当然,效果很好。
问题
有谁能深入了解为什么在一个MultiPartFile复制到本地文件的web服务器中,TFileOutputStream不能正确地写入?
发布于 2013-02-02 09:37:20
在长期运行的服务器应用程序中,您可能需要添加对TVFS.sync()或TVFS.umount()的调用,以同步或同步umount存档文件。对于ZIP文件,这将触发在ZIP文件末尾写入,这是形成有效ZIP文件所必需的。
请检查Javadoc以确定哪个调用最适合您的用例:http://truezip.java.net/apidocs/de/schlichtherle/truezip/file/TVFS.html
另外,请注意,每次追加操作后调用TFVS.sync()或TVFS.umount()将导致每次编写一个不断增长的中央目录,这将导致巨大的开销。所以值得考虑的是,你需要在什么时候这样做。一般来说,只有当您希望第三方访问ZIP文件时,才需要这样做。第三方是没有与TrueZIP内核交互以访问ZIP文件的人。
https://stackoverflow.com/questions/14637430
复制相似问题