Reputation: 169
I have searched and searched for an example of how to do this, but I have yet to find one.
I have a log file and in this log file it will have a list of files. I then need to move the files that were scanned in to a quarantined folder and retain directory structure. So far I have the following code:
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);
}
}
}
}
This works and successfully moves the files, but it does not maintain directory structure.
Any help is much appreciated.
Upvotes: 1
Views: 2621
Reputation: 6173
Try something like this:
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);
}
}
}
Upvotes: 4