jon givony
jon givony

Reputation: 197

FileAlreadyExistsException when using Files.copy

I am trying to copy a file from an InputStream into a local directory. I created a local directory called test, and it is located in my package root.

public void copyFileFromInputStream(InputStream is) {
    Path to = Paths.get("test");
    Files.copy(is, to);
}

Clearly I am misunderstanding Files.copy(...), because it seems like it is trying to create a new file called "test" instead of placing the file into the directory "test".

How do I write the file into the directory?

Upvotes: 1

Views: 2861

Answers (4)

3omar
3omar

Reputation: 170

You can use the option StandardCopyOption.REPLACE_EXISTING :

    public void copyFileFromInputStream(InputStream is) {
        Path to = Paths.get("test");
        Files.copy(is, to, StandardCopyOption.REPLACE_EXISTING);
    }

Upvotes: 0

Hanamant Guggari
Hanamant Guggari

Reputation: 39

Here is a answer for you question:

Referring to you code snippet: Paths.get("test"); you're asking a file path to the file named "test" in the current directory but not the directory. If you want to refer the file under test directory which in tern under your current directory. use the following: Paths.get("test/filename.ext") to which you want to write your stream data.

If you run your app twice, you get "FileAlreadyExistsException" because copy method on Files writes to new file , if exists it'll not override it.

I hope this helps you!

Upvotes: 2

HammerNL
HammerNL

Reputation: 1841

First create the new directory, then copy the stream to a new file in that directory:

Path to = Paths.get("mynewdir/test");
Files.copy(is, to);

Also bare in mind that your InputStream does not have a filename, so you will always need to provide a filename when writing the stream to disk. In your example, it will indeed try to create a file 'test', but apparently that is a folder that already exists (hence the Exception). So you need to specify the full filename.

Upvotes: 3

Jason
Jason

Reputation: 11832

The 'to' parameter of Files.copy(from, to) is the path to the destination file.

Try specifying what file name inside the test directory:

Path to = Paths.get("test/newfilename");
Files.copy(is, to);

Upvotes: 1

Related Questions