如何在java中复制文件

2022-09-04 23:45:31

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

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

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


答案 1

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


答案 2

使用 Java 7:

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

Files.copy(source, target, REPLACE_EXISTING);

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


推荐