从Java列表中复制文件,同时维护目录结构

时间:2012-01-23 16:11:02

标签: java copy

我搜索并搜索了一个如何执行此操作的示例,但我还没有找到一个。

我有一个日志文件,在这个日志文件中它将有一个文件列表。然后,我需要将扫描的文件移动到隔离文件夹并保留目录结构。到目前为止,我有以下代码:

public static void main(String[] args)   throws FileNotFoundException, IOException
{  
    String logPath = "C:\\apache-ant-1.8.2\\build\\LogFiles\\DoScan.log";
    String safeFolder = "C:\\apache-ant-1.8.2\\build\\Quaratined";  
    ArrayList<File> files = new ArrayList<File>();
    BufferedReader br = new BufferedReader(new FileReader( logPath ));
    String line = null;


    while ((line = br.readLine()) != null) 
    {
        Pattern pattern = Pattern.compile("'[a-zA-Z]:\\\\.+?'");
        Matcher matcher = pattern.matcher( line );

        if (matcher.matches()) 
        {
        }
        if (matcher.find()) 
        {
                String s = matcher.group(); 
                s = s.substring(1, s.length()-1); 
                files.add(new File(s));

                System.out.println("File found:" + files.get(files.size() - 1));
        }
    }



    for (File f : files) 
    {

        // Make sure we get a file indeed
            if (f.exists()) 
        {   
            if (!f.renameTo(new File(safeFolder, f.getName()))) 
            {
                        System.out.println("Moving file: " + f + " to " + safeFolder);
                        System.err.println("Unable to move file: " + f);
            }
        } 
        else 
        {
            System.out.println("Could not find file: " + f);
        }
    }   
}

}

这样可以成功移动文件,但不会维护目录结构。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

尝试这样的事情:

   public static void main(String[] args) throws IOException {
    String logPath = "/tmp/log";
    String safeFolder = "/tmp/q";
    ArrayList<File> files = new ArrayList<File>();
    BufferedReader br = new BufferedReader(new FileReader(logPath));
    String line = null;


    while ((line = br.readLine()) != null) {
            files.add(new File(line));

            System.out.println("File found:" + files.get(files.size() - 1));
    }

    String root = "/tmp/" ;

    for (File f : files && f.isFile()) {

        if (f.exists()) {
            File destFile = new File(safeFolder, f.getAbsolutePath().replace(root,""));
            destFile.getParentFile().mkdirs();
            if (!f.renameTo(destFile)) {
                System.out.println("Moving file: " + f + " to " + safeFolder);
                System.err.println("Unable to move file: " + f);
            }
       } else {
            System.out.println("Could not find file: " + f);
        }
    }
}