Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中使用apache commons vfs2访问后删除zip文件_Java_Json_Javafx_Zip_Apache Commons Vfs - Fatal编程技术网

在Java中使用apache commons vfs2访问后删除zip文件

在Java中使用apache commons vfs2访问后删除zip文件,java,json,javafx,zip,apache-commons-vfs,Java,Json,Javafx,Zip,Apache Commons Vfs,我正在尝试使用ApacheCommonsVFS2来读取zip文件的内容,就像它只是另一个目录一样。zip文件最终将保存所有类型的文件(甚至可能是一个小数据库) 为了便于说明,我创建了一些zip文件,其中包含一个名为project.json的文件,该文件是一个项目的json,带有名称和说明。当我得到zip文件时,我想读取json文件以从内部获取项目定义信息等 这一切都很好。现在,我希望我的用户能够从应用程序中删除这些文件。这就是事情对我不利的地方 我想我关闭了所有的输入流等等,但是应用程序中的文件

我正在尝试使用ApacheCommonsVFS2来读取zip文件的内容,就像它只是另一个目录一样。zip文件最终将保存所有类型的文件(甚至可能是一个小数据库)

为了便于说明,我创建了一些zip文件,其中包含一个名为project.json的文件,该文件是一个项目的json,带有名称和说明。当我得到zip文件时,我想读取json文件以从内部获取项目定义信息等

这一切都很好。现在,我希望我的用户能够从应用程序中删除这些文件。这就是事情对我不利的地方

我想我关闭了所有的输入流等等,但是应用程序中的文件似乎有一个锁,不允许我删除它

  • 如果我在应用程序的上下文中创建zip文件,我可以删除它
  • 如果我从文件系统中读取它,并且没有使用vfs2访问它,那么我可以删除它
  • 如果我从文件系统读取它并使用vfs2访问它,则不允许删除它
如果您想创建自己的zip文件来尝试,这里有一个简单的json字符串

{"project": {"name": "ProjectX", "description": "X is a project."}}
将其复制到名为project.json的文件中,并保存它。然后,将其压缩到Java项目根目录中的zip文件中

下面的例子说明了我的困境:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.json.JSONObject;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.stage.Stage;

public class FileLockExample extends Application {

    @Override
    public void start(Stage arg0) throws Exception {
        ObservableList<File> files = retrieveFiles();
        deleteFiles(files);
        Platform.exit();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

    public ObservableList<File> retrieveFiles() {
        File[] files = new File(".").listFiles(new FilenameFilter() { 
            @Override 
            public boolean accept(File dir, String name) { 
                return name.endsWith(".zip");
            }
        });
        for (File file : files) {
            try {
                FileSystemManager fsManager = VFS.getManager();
                FileObject zipFile = fsManager.resolveFile("zip:" + file.toURI());
                FileObject projectJson = fsManager.resolveFile(zipFile, "project.json");
                FileContent content = projectJson.getContent();

                InputStream in = content.getInputStream();
                byte[] buffer = new byte[1024];
                StringBuilder sb = new StringBuilder();
                int len;
                while ((len = in.read(buffer)) > 0) {
                    sb.append(new String(buffer, 0, len));
                }
                in.close();
                String json = sb.toString();

                JSONObject obj = new JSONObject(json);
                String name = obj.getJSONObject("project").getString("name");
                String description = obj.getJSONObject("project").getString("description");
                System.out.println("Found project : " + name + "(" + description + ")");
                content.close();
                projectJson.close();
                zipFile.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return FXCollections.observableArrayList(files);
    }

    public void deleteFiles(ObservableList<File> files) {
        for (File file : files) {
            System.out.println("Deleting " + file.getName());
            file.deleteOnExit();
        }
    }
}
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FilenameFilter;
导入java.io.IOException;
导入java.io.InputStream;
导入org.apache.commons.vfs2.FileContent;
导入org.apache.commons.vfs2.FileObject;
导入org.apache.commons.vfs2.FileSystemManager;
导入org.apache.commons.vfs2.VFS;
导入org.json.JSONObject;
导入javafx.application.application;
导入javafx.application.Platform;
导入javafx.collections.FXCollections;
导入javafx.collections.ObservableList;
导入javafx.stage.stage;
公共类FileLockExample扩展了应用程序{
@凌驾
public void start(阶段arg0)引发异常{
ObservableList files=检索文件();
删除文件(文件);
Platform.exit();
}
公共静态void main(字符串[]args){
应用程序启动(args);
}
公共可观察列表检索文件(){
File[]files=新文件(“.”)。listFiles(新文件名筛选器(){
@凌驾
公共布尔接受(文件目录,字符串名称){
返回名称.endsWith(“.zip”);
}
});
用于(文件:文件){
试一试{
FileSystemManager fsManager=VFS.getManager();
FileObject zipFile=fsManager.resolveFile(“zip:+file.toURI());
fileobjectprojectjson=fsManager.resolveFile(zipFile,“project.json”);
FileContent=projectJson.getContent();
InputStream in=content.getInputStream();
字节[]缓冲区=新字节[1024];
StringBuilder sb=新的StringBuilder();
内伦;
而((len=in.read(buffer))>0){
sb.append(新字符串(缓冲区,0,len));
}
in.close();
字符串json=sb.toString();
JSONObject obj=新的JSONObject(json);
String name=obj.getJSONObject(“项目”).getString(“名称”);
String description=obj.getJSONObject(“项目”).getString(“说明”);
System.out.println(“找到的项目:“+name+”(“+description+”)”);
content.close();
projectJson.close();
zipFile.close();
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
返回FXCollections.observableArrayList(文件);
}
公共无效删除文件(可观察列表文件){
用于(文件:文件){
System.out.println(“删除”+文件.getName());
deleteOnExit()文件;
}
}
}

鉴于似乎没有人对我的问题感兴趣,这促使我思考在本例中使用Apache Commons VFS的问题。我决定探索其他选择,并通过使用java.nioapi实现了我的短期目标。现在,我们继续实现一个长期目标,即尝试在zip文件中存储其他类型的文件,并以随机方式访问它们

如果有人关心,下面是我的示例代码,可以从文件系统中读取和删除zip文件,而不必求助于
InputStream
OutputStream

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.nio.file.spi.FileSystemProvider;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.stage.Stage;

public class FileLockExample extends Application {

    @Override
    public void start(Stage arg0) throws Exception {
        ObservableList<File> files = retrieveFiles();
        deleteFiles(files);
        Platform.exit();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

    public ObservableList<File> retrieveFiles() {
        File[] files = new File(".").listFiles(new FilenameFilter() { 
            @Override 
            public boolean accept(File dir, String name) { 
                return name.endsWith(".zip");
            }
        });
        for (File file : files) {
            try {
                Map<String, Object> env = new HashMap<>();
                FileSystemProvider provider = getZipFSProvider();
                URI uri = new URI("jar:" + file.toURI());
                FileSystem zipfs = provider.newFileSystem(uri, env);
                List<String> jsonList = Files.readAllLines(zipfs.getPath("/project.json"));
                StringBuilder sb = new StringBuilder();
                for (String string : jsonList) {
                    sb.append(string);
                }
                String json = sb.toString();
                JSONObject obj = new JSONObject(json);
                String name = obj.getJSONObject("project").getString("name");
                String description = obj.getJSONObject("project").getString("description");
                System.out.println("Found project : " + name + " (" + description + ")");
            } catch (URISyntaxException use) {
                use.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return FXCollections.observableArrayList(files);
    }

    public void deleteFiles(ObservableList<File> files) {
        for (File file : files) {
            System.out.println("Deleting " + file.getName());
            file.deleteOnExit();
        }
    }

    private static FileSystemProvider getZipFSProvider() {
        for (FileSystemProvider provider : FileSystemProvider.installedProviders()) {
            if ("jar".equals(provider.getScheme()))
                return provider;
        }
        return null;
    }

}
导入java.io.File;
导入java.io.FilenameFilter;
导入java.io.IOException;
导入java.net.URI;
导入java.net.URISyntaxException;
导入java.nio.file.*;
导入java.nio.file.spi.FileSystemProvider;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
导入org.json.JSONObject;
导入javafx.application.application;
导入javafx.application.Platform;
导入javafx.collections.FXCollections;
导入javafx.collections.ObservableList;
导入javafx.stage.stage;
公共类FileLockExample扩展了应用程序{
@凌驾
public void start(阶段arg0)引发异常{
ObservableList files=检索文件();
删除文件(文件);
Platform.exit();
}
公共静态void main(字符串[]args){
应用程序启动(args);
}
公共可观察列表检索文件(){
File[]files=新文件(“.”)。listFiles(新文件名筛选器(){
@凌驾
公共布尔接受(文件目录,字符串名称){
返回名称.endsWith(“.zip”);
}
});
用于(文件:文件){
试一试{
Map env=new HashMap();
FileSystemProvider provider=getZipFSProvider();