我正在研究一个程序文件系统的概念。我是用Java写的(使用JDK 7 u17)。
为了开始,我构建了一些教程,展示了如何使用FileSystemProvider类创建基于zip的文件系统。
当我执行代码时,我让它执行与示例类似的任务,即从我的桌面复制文本文件并将其放入zip文件中。问题是一旦它复制了文件,它不会将其写入zip文件,它似乎将文件留在内存中,当程序终止时将被销毁。
问题是我不明白为什么,据我所知,一切看起来都是有序的,但有些东西显然不是!
哦,对了,目录也是如此。如果我告诉文件系统创建一个新目录,它只是在内存中创建它,zip文件中没有任何内容。
无论如何,这是我的工作代码;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class Start {
public static void main(String[] args) {
Map <String, String> env = new HashMap<>();
env.put("create", "true");
env.put("encoding", "UTF-8");
FileSystem fs = null;
try {
fs = FileSystems.newFileSystem(URI.create("jar:file:/Users/Ian/Desktop/test.zip"), env);
} catch (IOException e) {
e.printStackTrace();
}
Path externalTxtFile = Paths.get("/Users/Ian/Desktop/example.txt");
Path pathInZipFile = fs.getPath("/example.txt");
try {
Files.createDirectory(fs.getPath("/SomeDirectory"));
} catch (IOException e) {
e.printStackTrace();
}
if (Files.exists(fs.getPath("/SomeDirectory"))) {
System.out.println("Yes the directory exists in memory.");
} else {
System.out.println("What directory?");
}
// Why is the file only being copied into memory and not written out the jar/zip archive?
try {
Files.copy(externalTxtFile, pathInZipFile);
} catch (IOException e) {
e.printStackTrace();
}
// The file clearly exists just before the program ends, what is going on?
if (Files.exists(fs.getPath("/example.txt"))) {
System.out.println("Yes the file has been copied into memory.");
} else {
System.out.println("What file?");
}
}
}
我只是想添加一些东西。也许你发现的例子是不完整的(我不能检查,因为你没有引用它),但在所有的例子中,我发现文件系统实例是正确关闭的。
文件系统抽象类实现了Closeable,所以close()方法被调用(自动),在下面的代码中留下try:
try (final FileSystem fs = FileSystems.newFileSystem(theUri, env)) {
/* ... do everything you want here ; do not need to call fs.close() ... */
}
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html