Amal Kostali Targhi Amal Kostali Targhi - 28 days ago 9
Java Question

arrayList<File> to folder containing those files java

I have an

ArrayList<File>
.

And I need to write those files into a output_Directory into my computer

this is my code

for (File file : corpus)


{
try {
FileWriter fw = new FileWriter (new File(outDirName, file.getName()));
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter out = new PrintWriter (bw);
out.close();
}
catch (Exception e){
System.out.println(e.toString());
}
}


the corpus is the arraylist of files

the error is

java.io.FileNotFoundException: Diroutput/name of my file


(no files or directories of this types)

Answer

Most likely your output directory doesn't exist. So create the output directory first and the error is gone. Also, you can use Files.copy() from java.nio.file which will avoid to create multiple FileWriter instances

try {
    Files.copy(
        Paths.get(file.getAbsolutePath()),
        Paths.get(new File("<correct Path>", file.getName()).getAbsolutePath()));
} catch (IOException e) {
    e.printStackTrace();
} 
Comments