java - java中复制文件的方法

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

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

最佳答案

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

关于java - java中复制文件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5003907/

相关文章:

java - 如何在 Html/JavaScript 中实现绑定(bind)到 Java 对象集合的可编辑网格控件?

java - 如何将 mysql 驱动程序 jar 添加到项目作为 github 存储库的依赖项?

Java返回数组并删除最后一项?

java - OpenJDK 64 位服务器 VM 警告 : You have loaded library which might have disabled stack guard

java - RJDBC Cassandra -> .jfindClass 错误(as.character(driverClass)[1]): class not found

java.lang.OutOfMemoryError : Direct buffer memory when invoking Files. 读取所有字节

java - Android,org.simpleframework.xml 持久化异常,元素 'foo' 已被使用

java - 在 JPanel 中调整图像大小

java - Localdate.format,格式不适用

java - IntelliJ IDEA 是否内置反向调试功能?