user2875333
user2875333

Reputation: 11

Alternative to move files

I wonder if there is any other way to move files from one directory to another, a snippet of my program is below. I believe there should be an efficient way to move files in java. Please take a look and respond if possible. Thanks!

public static void movFile(File pathFromMove,File pathToMove,File fileToMove)    //helper method 2
{

    String absPathFile2= pathToMove.getAbsolutePath() + "\\"+fileToMove.getName();                                                              //{

    InputStream inStream = null;
    OutputStream outStream = null;

    try
    {
        //System.out.println("i am here no1");
        inStream= new FileInputStream(fileToMove);
        outStream=new FileOutputStream(absPathFile2);
        byte[] buffer = new byte[1024];


        int length;
        while (( length = inStream.read(buffer)) > 0)
        {

            outStream.write(buffer, 0, length);
            //System.out.println("i am here no2");

        }
      inStream.close();
        outStream.close();
        fileToMove.delete();            //to delete the original files
    //  System.out.println("i am here no3");

    }
    catch(IOException e)
    {
        //System.out.println("i am here no4");

        e.printStackTrace();
    }

}

Upvotes: 1

Views: 171

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

If it's on the same disk, the File.renameTo would be efficient

I'm not sure why you would need 3 File references, two should be enough...but it's your code...

For example...

public static void movFile(File pathFromMove,File pathToMove,File fileToMove) throws IOException {

    File from = new File(pathFromMove + File.separator + fileToMove);
    File to = new File(pathToMove+ File.separator + fileToMove);

    if (!from.renameTo(to)) {
        throw new IOException("Failed to move " + from + " to " + to);
    }

}

You can alos have a look at Moving a File or Directory which uses the new Paths API available in Java 7

Upvotes: 2

Related Questions