3

I am trying to copy a file to a path that may not exist with this code

    public static void copyFile( File from, File to ) throws IOException {

    if ( !to.exists() ) { to.createNewFile(); }

    try (
        FileChannel in = new FileInputStream( from ).getChannel();
        FileChannel out = new FileOutputStream( to ).getChannel() ) {

        out.transferFrom( in, 0, in.size() );
    }

which is obviously wrong because if the directory does not exist it wouldn't copy the file. It needs to create the folders that do not exist in the path.

For example the program should copy a file to:

C:\test\test1\test2\test3\copiedFile.exe

where the directory test in C:\ exists but test2 and test3 are missing, so the program should create them.

Nick Nikolov
  • 261
  • 3
  • 13
  • So you'll have to [create](http://docs.oracle.com/javase/8/docs/api/java/io/File.html#mkdirs--) the directory. – 5gon12eder Feb 19 '15 at 18:38

1 Answers1

6

You can create all paths with the code snippet below, e.g.:

File file = new File("C:\\test\\test1\\test2\\test3\\copiedFile.exe");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
Trinimon
  • 13,839
  • 9
  • 44
  • 60