Moving txt files to a folder instead of deleting them in java
i have a code to concatenate txt files from a folder and move the concatenated file in another folder. My code is working well but it deletes files after concatenating them so i would like to move these files to another folder just after concatenating them.
My files from c:\source must be moved to c:\Archive
It was my mistake at the starting, i wanted to move files but i delete them!! And i would like to throw exception when there is no files in the source folder.
So my code is:
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Target/Filec.txt"));// directory where concatenated file are created
File file = new File("C:/Source");// where files have to be concatenated and move to c:\Archive before deleting
File[] files2 = file.listFiles();
for (int i = 0; i < files2.length; i++)
{
File currentFile = files2[i];
System.out.println("Processing " + currentFile.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(currentFile));
开发者_运维问答String line = br.readLine();
while (line != null)
{
pw.println(line);
line = br.readLine();
}
br.close();
if (!currentFile.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+ currentFile.getName());
}
}
pw.close();
System.out.println("All files have been concatenated into Filec.txt");
}
}
Thank you
To move a file you use source.renameTo(targetFile)
.
If there are no files in the source dir then listFiles()
will return an empty array so just check for that and throw.
Also if you just want to blindly concat files you don't need to read line by line, just open a FileInputStream, read chunks into a byte[] and write using a FileOutputStream. Likely to be much more efficient and simpler.
You can move a file like so:
// File (or directory) to be moved
File file = new File("filename");
// Destination directory
File dir = new File("directoryname");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
// File was not successfully moved
}
Instead of File.delete() use FileUtils.moveFile() from apache commons
精彩评论