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

时间:2011-11-04 05:54:05

标签: 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)

1 个答案:

答案 0 :(得分:2)

destination应该是FileOutputStream,对吧?

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

如果您只想复制或移动文件,则应使用FileUtils中的Apache Commons。有moveFile方法和copyFile方法。

相关问题