Nick Nikolov
Nick Nikolov

Reputation: 261

Copy file in java to directory that may not exist

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.

Upvotes: 3

Views: 4221

Answers (1)

Trinimon
Trinimon

Reputation: 13957

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

Upvotes: 6

Related Questions