2013-04-23 97 views
0

如何給args [0]中的源文件和args [1]中的目標文件?我在同一個包中創建了一個source.txt和一個target.txt,並在運行配置中放入了「./source.txt」和「./target.txt」作爲參數。但它會拋出「./source.txt」不可讀取的異常。Paths.get(args [0])不起作用

Exception in thread "main" java.lang.IllegalArgumnetException: ./source.txt 

什麼是worng?

import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.nio.file.StandardCopyOption; 
import de.sb.javase.TypeMetadata; 


/** 
    * Demonstrates copying a file using a single thread. 
*/ 
public final class FileCopyLinear { 

/** 
* Copies a file. The first argument is expected to be a qualified source file name, 
* the second a qualified target file name. 
* @param args the VM arguments 
* @throws IOException if there's an I/O related problem 
*/ 
public static void main(final String[] args) throws IOException { 
    final Path sourcePath = Paths.get(args[0]); 
    if (!Files.isReadable(sourcePath)) throw new IllegalArgumentException(sourcePath.toString()); 

    final Path sinkPath = Paths.get(args[1]); 
    if (sinkPath.getParent() != null && !Files.isDirectory(sinkPath.getParent())) throw new IllegalArgumentException(sinkPath.toString()); 

    Files.copy(sourcePath, sinkPath, StandardCopyOption.REPLACE_EXISTING); 

    System.out.println("done."); 
} 
} 
+1

「./source.txt」 不readdable?我希望實現者不會犯這種拼寫錯誤。總是複製粘貼原始堆棧跟蹤 – 2013-04-23 10:01:58

+1

什麼是「異常」的詳細信息(類型,消息,合理詳細的堆棧跟蹤)? – 2013-04-23 10:02:37

+0

是不是args [0]你正在擅長的.java文件?還是僅僅在C++中? – 2013-04-23 10:03:38

回答

4

相對文件路徑不是相對於包的任何類的。它們與當前目錄相關,該目錄是執行java命令以啓動程序的目錄。

所以,如果你在目錄/home/user1477955並鍵入

/home/user1477955 > java com.foo.bar.FileCopyLinear source.txt target.txt 

它將搜索文件/home/user1477955/source.txt/home/user1477955/target.txt

+0

你是完全正確的,非常感謝你的快速反應 – user1477955 2013-04-23 10:17:41

0

你可以試試這個:

try { 
     File file = new File(args[0]); 
     BufferedReader in = new BufferedReader(new FileReader(file)); 
     //rest of your code 
     in.close(); 
    } catch (IOException e) { 
     System.out.println("File Read Error: " + e.getMessage()); 
    } 
+1

如果路徑錯誤或文件不可讀,這將無濟於事。 – NilsH 2013-04-23 10:05:54