user236501
user236501

Reputation: 8648

Java copy and rename image file into another directory

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

I am using the code above to copy image file and rename the image file into another directory if user input itemname = "music", I want the image name rename to music. the image extension

But I got this exception

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

Upvotes: 0

Views: 5878

Answers (1)

ObscureRobot
ObscureRobot

Reputation: 7336

destination should probably be a FileOutputStream, right?

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

If you just want to copy or move a file, you should use FileUtils from Apache Commons. There is a moveFile method and a copyFile method.

Upvotes: 2

Related Questions