Michael A
Michael A

Reputation: 5840

Problem with moving a file to another folder

I am using:

// File (or directory) to be moved
    File file = new File(output.toString());



    // Destination directory
    File dir = new File(directory_name);

    // Move file to new directory
    boolean success = file.renameTo(new File(dir, new_file.getName()));
    if (!success) {
        // File was not successfully moved
    }

In this case file is main.vm, and folder is seven the program shows that it works(the file exists and all) but the file is not moving to the seven directory. Any ideas why?

Is it ok that the file name is main.vm or do i need to enter full path? the same for the folder. Thanks

Upvotes: 1

Views: 637

Answers (4)

surlac
surlac

Reputation: 2961

Try to do following steps:

  1. check if you move the file inside same filesystem - otherwise it will fail;
  2. create destination directory;
  3. define "new_file" variable.

Upvotes: 2

alphazero
alphazero

Reputation: 27224

Works for me. (run with java -ea opt.)

    File f = new File("foo.mv");
    if(!f.exists()) 
        assert f.createNewFile() : "failed to create foo.mv";

    File folder = new File("7");
    if(!folder.exists())
        assert folder.mkdir() : "failed to create new directory";

    File fnew = new File(folder, f.getName());
    assert !fnew.exists() : "fnew already exists";
    f.renameTo(fnew);
    assert fnew.exists() : "fnew does not exist -- move failed";

    System.out.format("moved %s to %s\n",f, fnew);

Upvotes: 2

Omnaest
Omnaest

Reputation: 3096

Maybe you wanna take a look at the Apache Commons FileUtils

Upvotes: 2

Denees
Denees

Reputation: 9198

You need to enter full path of the file, not only the filename. And would be nice if you'll show up your full source code in the future, for better understanding/answers.

Upvotes: 1

Related Questions