Java将图像文件复制并重命名到另一个目录中

标签 java file

   String name = "";
   File destFile = new File(folderPath + catalogueFileName + itemName.getText());
   if (!destFile.exists()) {
       destFile.createNewFile();
   }

   FileChannel fileSource = new FileInputStream(imagePath).getChannel();
   FileChannel destination = new FileInputStream(folderPath
       + catalogueFileName ).getChannel();
   destination.transferFrom(fileSource, 0, fileSource.size());

   JOptionPane.showMessageDialog(null, "A new entry added successfully.");
   if (fileSource != null) {
       fileSource.close();
   }
   if (destination != null) {
       destination.close();
   }

我正在使用上面的代码复制图像文件并将图像文件重命名到另一个目录,如果用户输入 itemname =“music”,我希望图像名称重命名为音乐。图片扩展

但是我遇到了这个异常

Exception occurred during event dispatching:
java.nio.channels.NonWritableChannelException
    at sun.nio.ch.FileChannelImpl.transferFrom(FileChannelImpl.java:584)

最佳答案

destination 可能应该是 FileOutputStream,对吗?

FileChannel destination = new FileOutputStream(folderPath
       + catalogueFileName).getChannel();

如果您只想复制或移动文件,则应该使用 FileUtils来自Apache Commons 。有一个moveFile方法和copyFile方法。

关于Java将图像文件复制并重命名到另一个目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8005389/

相关文章:

php - 如何通过 PHP 中的 Web 服务发送/获取文件

file - 德尔福6 : How can I change created filedate (= file creation date)

java - 将log4j2与slf4j一起使用:java.lang.StackOverflowError

java - 该配置引用了未知类 'String'

java - 如何编写访问器和修改器?

java - Mybatis spring改造参数

c - C 中的文本文件到数组

c++ - QFile/QTextStream 在写入删除文件时不显示错误

java - 在本地安全地保存密码java?

java - WebSockets 或 Http 哪一个用于实时应用程序?