gpt4 book ai didi

java - 这是复制文件的有效方法吗

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:22 25 4
gpt4 key购买 nike

这是复制目录(包括子目录)中所有文件的有效方法吗?是否有无限递归的可能?有什么我应该改变的吗?我知道它有效,但我认为应该有一种更简单的方法来做到这一点。

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();
}

}
}

谢谢

最佳答案

正如评论所示,看起来相当不错。您可能想研究新的 Java 7 API(新的 NIO)。有教程here ,看起来甚至还有避免跟随链接的选项。

如果你不能使用Java 7,旧的NIO有 channel ,你可以用旧的方式打开文件后打开。它们包括方法 transferFromtransferTo ,这可能比 Java 更高效。

关于java - 这是复制文件的有效方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8663521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com