我已经使用InputStream将文件从一个位置成功复制到另一个位置:
public static void copy(File src, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream("C:\\test.txt");
os = new FileOutputStream("C:\\javatest\\test.txt");
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(buf)) > 0) {
os.write(buf, 0, bytesRead);
}
} finally {
is.close();
os.close();
}
}
我在路径中添加不存在的文件夹时出现问题,例如:
os = new FileOutputStream("C:\\javatest\\javanewfolder\\test.txt");
这将返回NullPointerException错误。在通过输出流执行复制过程时,如何创建所有缺少的目录?
首先,如果可能,我建议您使用java.nio.file类(例如Path),而不是基于文件的方法。您将使用文件系统创建Path对象。如果此处不需要灵活性,您可以使用默认文件系统:
final String folder = ...
final String filename = ...
final FileSystem fs = FileSystems.getDefault();
final Path myFile fs.getPath(folder, filename);
然后通过一个非常方便的API轻松解决您的问题:
final Path destinationFolder = dest.getParent();
Files.createDirectories(myPath.getParent());
try (final OutputStream os = Files.newOutputStream(myFile)) {
...
}
如果目录已存在,则Files.createDirectories()方法不会失败,但由于其他原因,它可能会失败。例如,如果存在文件“foo / bar”,则Files.createDirectories(“foo / bar / folder”)很可能不会成功。 ;)
请仔细阅读javadoc!
要检查路径是否指向现有目录,只需用户:
Files.isDirectory(somePath);
如果需要,您可以在文件和路径之间进行转换。但是,您将丢失文件系统信息:
final Path path1 = file1.toPath();
final File file2 = path2.toFile();
你可以使用Files.createDirectories:
Files.createDirectories(Paths.get("C:\\javatest\\javanewfolder"));
此外,你可以使用Files.copy
来复制文件)