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/