Search code examples
javafilecopycross-platformmove

Move file without using renameTo()


In my Java program, I would like to display the progress of moving a file. I use the following snippet of code to copy files, which allows me to track the bytes copied and shows it in a progress bar. I was wondering if the code code be adapted to move files rather than just copy them?

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));


            int theByte;

            while((theByte = bis.read()) != -1)
            {
                bos.write(theByte);

            }

            bis.close();
            bos.close();

Solution

  • Okay, so a "move" operation is a copy with a "delete" at the end, for example...

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    
    try {
        bis = new BufferedInputStream(new FileInputStream(sourceFile));
        bos = new BufferedOutputStream(new FileOutputStream(targetFile));
    
        int theByte;
    
        while((theByte = bis.read()) != -1)
        {
            bos.write(theByte);
        }
    
        bos.close();
        bis.close();
        // You may want to verify that the file's are the same (ie the file size for example)
        if (!sourceFile.delete()) {
            throw new IOException("Failed to remove source file " + sourceFile);
        }
    
    } catch (IOException exp) {
        exp.printStackTrace();
    } finally {
        try {
            bis.close();
        } catch (Exception exp) {
        }
        try {
            bos.close();
        } catch (Exception exp) {
        }
    }