gpt4 book ai didi

java - 在 Java 中维护目录结构的同时从列表中复制文件

转载 作者:行者123 更新时间:2023-11-29 03:50:36 25 4
gpt4 key购买 nike

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

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

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

这有效并成功地移动了文件,但它不维护目录结构。

非常感谢任何帮助。

最佳答案

尝试这样的事情:

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

关于java - 在 Java 中维护目录结构的同时从列表中复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8974731/

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