如何在java中复制文件

Pet*_*ter 12 java

我试图在java中复制文件并将其移动到新文件夹.这是我一直在使用的代码,但我总是在指定的目录中收到此错误"(访问被拒绝)".有没有办法可以解决这个或更好的方法来复制文件?谢谢

try{
          File f1 = new File(fpath);
          File f2 = new File("C:/users/peter/documents/foldertest2/hats");
          InputStream in = new FileInputStream(f1);

          //For Append the file.
          //OutputStream out = new FileOutputStream(f2,true);

          //For Overwrite the file.
          OutputStream out = new FileOutputStream(f2);

          byte[] buf = new byte[1024];
          int len;
          while ((len = in.read(buf)) > 0){
            out.write(buf, 0, len);
          }
          in.close();
          out.close();
          System.out.println("File copied.");
        }
        catch(FileNotFoundException ex){
          System.out.println(ex.getMessage() + " in the specified directory.");
          System.exit(0);
        }
        catch(IOException e){
          System.out.println(e.getMessage());      
        }
Run Code Online (Sandbox Code Playgroud)

更新:我检查了文件夹权限,它们对所有用户和我的所有用户都是开放的

Dea*_*mer 36

Apache Commons IO也是另一种方式,特别是FileUtils.copyFile();它可以为您处理所有繁重的工作.


kpa*_*vel 18

使用Java 7:

import static java.nio.file.StandardCopyOption.*;
Run Code Online (Sandbox Code Playgroud)
Files.copy(source, target, REPLACE_EXISTING);
Run Code Online (Sandbox Code Playgroud)

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


jos*_*efx 2

编辑ups搞砸了,第二次尝试:

您必须为 FileOutputStream 提供一个有效的文件名,只需将文件名附加到目标路径(C:/users/peter/documents/foldertest2/hats/hat3仅包含文件夹名称),它将尝试访问该文件夹,就好像它是一个文件一样,但会失败。