我正在研究一个程序的文件系统的概念。我正在用Java编写(使用JDK7 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?");
}
}
}发布于 2014-04-26 19:35:53
我只想补充一点。也许您找到的示例不完整(我无法检查,因为您没有引用它),但在所有示例中,我都发现FileSystem实例是正确关闭的。
FileSystem抽象类实现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
https://stackoverflow.com/questions/15609648
复制相似问题