1

我想知道是否有任何其他方法可以将文件从一个目录移动到另一个目录,下面是我的程序片段。我相信应该有一种有效的方法来在java中移动文件。如果可能,请查看并回复。谢谢!

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();
    }

}
4

1 回答 1

2

如果它在同一个磁盘上,那File.renameTo将是有效的

我不确定你为什么需要 3 个File引用,两个应该就足够了......但这是你的代码......

例如...

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);
    }

}

您还可以查看使用Java 7 中提供的新API 的移动文件或目录Paths

于 2013-10-15T02:32:30.657 回答