2

I am creating a file manager in java.I have a problem when I am trying to rename the files and folders.I am taking the new filename from user input then I am trying to rename the file.

popupMenu.rename.addActionListener(new ActionListener()
{           public void actionPerformed(ActionEvent e) {
                list.getSelectedValue().toString();
                JFrame frame = new JFrame("Rename");
                final JTextField textField=new JTextField();
                 String s = null;
                 File file2 = new File("newname");
                textField.addActionListener(new ActionListener(){
                       public void actionPerformed(ActionEvent ae){
                       s = textField.getText();
                       }
                    });
                Object o = list.getModel().getElementAt(list.getSelectedIndex());
                File file = new File(o.toString());
                //FileUtils.moveFile(file, newFile);
                  file.renameTo(file2);
                  //Files.move(file.toPath(),file.toPath().resolveSibling(textField.getText()));

                frame.add(textField);
                frame.setLocationRelativeTo(frame);
                frame.setSize(200,60);
                frame.setVisible(true);
            }
        });

Please suggest anything mistakes I made.

Also, is there a way I could rename the file similiar to windows by clicking on text.I am displaying the files and folders name by setText(fileName);.Here is my project screenshot

enter image description here

Reinard
  • 3,472
  • 10
  • 41
  • 59
Jaspreet Jolly
  • 1,145
  • 8
  • 25

1 Answers1

1

The problem is this line:

file.renameTo(file2);

You aren't looking at the return value, so if it fails, your code just acts like it succeeded.

java.io.File is obsolete. It is a holdover from Java 1.0, which had a handful of less than ideal design decisions. Among these was the decision to have many methods of the File class return a value, like C libraries do, instead of throwing an exception on failure.

Change that line of code to this:

Files.move(file.toPath(), file2.toPath());

The compiler will tell you that you have to catch IOException. That's a good thing. Do not write an empty catch block—that exception will tell you exactly why your attempt to rename the file is failing. At the very least, a catch block should call printStackTrace() on the caught exception.

VGR
  • 37,458
  • 4
  • 42
  • 54