作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试创建一个自定义文件复制器,它需要源文件夹、目标文件夹和包含一些文件名的数组列表。然后复制器复制ArrayList中的文件,结构相同。
仅当文件名与数组中的元素相同时,我才能通过复制来实现它。但它会创建所有文件夹,无论目标文件是否不存在于其中。
public static void main(String[] args) {
// TODO code application logic here
File source = new File("D:\\Documents\\A X");
File dest = new File("D:\\Documents\\A X Sample");
ArrayList<String> myFiles = new ArrayList<String>();
myFiles.add("Tohi - Rooh.mp3");
try{
copyDirectory(source, dest, myFiles);;
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}
}
public static void copyDirectory(File sourceLocation , File targetLocation, ArrayList<String> array)
throws IOException {
if (sourceLocation.isDirectory()) {
String[] children = sourceLocation.list();
for(String element : children){
if (array.contains(element)){
File fileToCopy = new File(sourceLocation, element);
//System.out.println(fileToCopy.getAbsolutePath());
targetLocation.mkdir();
}
//if (!targetLocation.exists()) {
// targetLocation.mkdir();
//}
}
for (int i=0; i<children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]), array);
}
} else {
if(array.contains(sourceLocation.getName())){
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
//System.out.println("File copied from " + sourceLocation + " to " + targetLocation);
}
}
}
所以我希望它停止创建无用的空白文件夹,并且仅在它们包含数组中的目标文件时才创建它们。有什么想法吗?
最佳答案
您正在为 sourceLocation
的每个子级调用方法 copyDirectory
。纠正它的方法(不是唯一或最好的)是将要复制的文件保存在 list
的 sourceDiretory
中。例如:
[...]
if (sourceLocation.isDirectory()) {
String[] children = sourceLocation.list();
// List to save the name of the files you want to copy
List<String> foundFiles = new ArrayList<String>(array.size());
for(String element : children){
if (array.contains(element)){
// If the file you want to copy are in the sourceDiretory
// add its name to the list
foundFiles.add(element);
targetLocation.mkdirs();
}
}
for (String foundFile : foundFiles) {
copyDirectory(new File(sourceLocation, foundFile),
new File(targetLocation, foundFile), array);
}
}
[...]
关于java - 如何仅复制给定文件而不是目录中的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28679074/
我是一名优秀的程序员,十分优秀!