Java 这是复制文件的有效方法吗
这是复制目录中所有文件(包括子目录)的有效方法吗?是否存在无限递归的可能性?有什么我该换的吗?我知道这是可行的,但我认为应该有一个更简单的方法Java 这是复制文件的有效方法吗,java,recursion,copy,Java,Recursion,Copy,这是复制目录中所有文件(包括子目录)的有效方法吗?是否存在无限递归的可能性?有什么我该换的吗?我知道这是可行的,但我认为应该有一个更简单的方法 private void copy(File file, String path) { String fileName = file.getPath(); System.out.println(fileName); fileName = fileName.substring(fileName.lastInd
private void copy(File file, String path) {
String fileName = file.getPath();
System.out.println(fileName);
fileName = fileName.substring(fileName.lastIndexOf("\\"));
if (path == null)
path = Storage.getStorageDirectoryPath();
File toWrite = new File(path + File.separator + fileName);
if (file.isDirectory()) {
toWrite.mkdir();
File inDirectory[] = file.listFiles();
for (File f : inDirectory)
copy(f, toWrite.getPath());
} else {
try {
InputStream inStream = new FileInputStream(file);
OutputStream outStream = new FileOutputStream(toWrite);
byte buffer[] = new byte[1024];
int length = 0;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
谢谢如评论所示,看起来不错。您可能需要研究新的Java7API(新的NIO)。有一个教程,它看起来甚至有避免以下链接的选项
如果您不能使用Java7,旧的NIO有一些通道,您可以在以旧的方式打开文件后打开这些通道。它们包括方法和,可能比Java更有效。如评论所示,看起来相当不错。您可能需要研究新的Java7API(新的NIO)。有一个教程,它看起来甚至有避免以下链接的选项
如果您不能使用Java7,旧的NIO有一些通道,您可以在以旧的方式打开文件后打开这些通道。它们包括方法和工具,可能比Java更有效。为什么要重新发明轮子?特别是看看Apache Common中的方法。为什么要重新发明轮子?特别是看看Apache Common中的方法。我认为它很有效。您使用的是什么版本的Java?Java 7为此提供了
文件
类。如果遇到从文件夹到上一个文件夹的符号链接
,我想你会遇到一个无限循环。我相信如果你使用而不是getPath
,你就不必担心符号链接,因为它们会为你解决。你为什么不使用Apache Common的FileUtils呢?我认为它很有效。你使用的是什么版本的Java?Java 7为此提供了文件
类。如果遇到从文件夹到上一个文件夹的符号链接
,我认为您将遇到无限循环。我相信如果您使用而不是getPath
,您将不必担心符号链接,因为它们将为您解决。为什么不使用Apache Common的FileUtils?