How to copy file in java

后端 未结 6 1901
后悔当初
后悔当初 2021-02-13 18:56

Im trying to copy a file in java and move it to a new folder. This is the code i HAve been using but I always get this error \"(Access is denied) in the specified directory\". I

相关标签:
6条回答
  • 2021-02-13 19:35

    Edit ups messed up, second try:

    You have to give the FileOutputStream a valid file name, just append the name of your file to the target path C:/users/peter/documents/foldertest2/hats/hat3 with only the folder name it will try to access the folder as if it was a file and fail.

    0 讨论(0)
  • 2021-02-13 19:41

    Apache Commons IO is also another way to go, specifically FileUtils.copyFile(); it handles all the heavy lifting for you.

    0 讨论(0)
  • 2021-02-13 19:41

    Use Java 7:

    import static java.nio.file.StandardCopyOption.*;
    

    Files.copy(source, target, REPLACE_EXISTING);
    

    http://docs.oracle.com/javase/tutorial/essential/io/copy.html

    0 讨论(0)
  • 2021-02-13 19:55

    Is there a way i can fix this or a better way to copy the files?

    If you have the option, I would recommend you to go with Java version 7, and use the Path.copyTo method.

    Copy the file located by this path to a target location. [...]

    Otherwise I would recommend at least using the NIO packages and FileChannels.

    0 讨论(0)
  • 2021-02-13 19:58

    Hmm it looks like you are trying to run this on windows, should you not be using \ in your path instead of / ?

    As AlexR said check your permissions on the directory you are trying to write to.

    0 讨论(0)
  • 2021-02-13 20:00

    If you get this exception the access is really denied, i.e. you just do not have rights to write to the specified directory or file. So, first check it. Try for example to create the file in specified directory manually. Do you probably try to create file in somebody else' home directory? Or your java program is running as other user? What about foldertest2? Does it exist and writable? Try to copy your file there.

    And the final tip. When you manage to copy the file, I'd recommend you to use IOUtils.copy() (from jacarta commons). I use it a lot. It does almost exactly what you implemented but have to write of code one line only.

    0 讨论(0)
提交回复
热议问题