2013-10-15 23 views
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(); 
    } 

} 
+0

使用system(),或者您最喜欢的库来隐藏您的系统。 – ChuckCottrill

回答

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

} 

您可以在Moving a File or Directory它使用可用的新Paths API在Java 7中阿洛斯看看

+0

要提出一个NIO备选/等效,请查看:http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move(java.nio.file.Path, java.nio.file.Path,java.nio.file.CopyOption ...) –

+0

@JoshM添加链接,真的没有经验...仍然卡在Java 6 :( – MadProgrammer

+0

:O你似乎是1(2,如果你计算Java 8早期版本)后面的版本:P我使用Java 8,这很好,你应该检查它:) –