Java-移动文件到另一个目录

Java-移动文件到另一个目录

Tags: Java

摘要

Java-移动文件到另一个目录

两种方法移动文件到另一个目录

Java.io.File 并没有直接提供移动文件到另一个目录的方法,可以通过下面两个方法间接实现。

  1. File.renameTo()
  2. 拷贝,然后删除源文件

代码实现

renameTo()

package cn.javacore.io.file;

import java.io.File;

public class _14_MoveFileExample1 {
    public static void main(String[] args) {
        try {

            File afile = new File("/home/zhu/folderA/Afile.txt");
            if (afile.renameTo(new File("/home/zhu/folderB/" + afile.getName()))) {
                System.out.println("File is moved successful!");
            } else {
                System.out.println("File is failed to move!");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

复制,再删除

package cn.javacore.io.file;

import java.io.*;

public class _14_MoveFileExample2 {
    public static void main(String[] args) {

        InputStream inStream = null;
        OutputStream outStream = null;

        try {

            File afile = new File("/home/zhu/folderA/Afile.txt");
            File bfile = new File("/home/zhu/folderB/Afile.txt");

            inStream = new FileInputStream(afile);
            outStream = new FileOutputStream(bfile);

            byte[] buffer = new byte[1024];

            int length;
            //copy the file content in bytes
            while ((length = inStream.read(buffer)) > 0) {

                outStream.write(buffer, 0, length);

            }

            inStream.close();
            outStream.close();

            //delete the original file
            afile.delete();

            System.out.println("File is copied successful!");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}