2012-03-01 46 views
-1

我嘗試輸入帶引號和無引號的文件名,但它仍然只處理第一個空格。即使路徑中沒有空格,也不會檢測到該文件,但路徑將正確顯示。如何解決它?當在java中打開文件時,「文件名,目錄名稱或卷標語法不正確」

Enter the filename: a b c 
java.io.FileNotFoundException: a (The system cannot find the file specified) 
Enter the filename: "a b c " 
java.io.FileNotFoundException: "a (The system cannot find the file specified) 

這是獲得文件輸入的最佳方式嗎? 此外,我應該添加拋出IOException,FileNotFoundException爲主或使用嘗試{},而不是?

System.out.print("Enter the filename: "); 

Scanner stdin = new Scanner((System.in)); //Keyboard input 
String nextDataValue, data, popped="", tag="", fileName=stdin.next(); 

FileInputStream fis = null; 
    try { 
     fis = new FileInputStream(fileName); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
InputStreamReader inStream = new InputStreamReader(fis); 
BufferedReader in = new BufferedReader(inStream); 

data=in.readLine(); 
+0

您正試圖讀取具有空格的文件名嗎? – 2012-03-01 02:56:14

+0

該路徑有空格。 – user93200 2012-03-01 02:57:25

+2

使用'nextLine()'而不是'next()',或者使用@MДΓΓБДLL的建議。 – chrisn 2012-03-01 02:59:32

回答

3

掃描儀很清楚地給你空格分隔的令牌。從the Scanner JavaDocs

Scanner打破其輸入到使用定界符模式,默認情況下與空白匹配。

所以你有它。我討厭這麼說,但這是一個RTFD的例子。

使用不同的分隔符,或使用Scanner#nextLine()而不是Scanner#next()

+0

然後你必須提供更多信息。 – 2012-03-01 03:02:49

相關問題