2016-03-01 74 views
0

我能夠通過指定文件路徑(位於我的src項目中)來讀取文件,但我試圖通過提供其名稱來讀取或打開文件用戶在第一個參數中被命令行提示。使用Java中的參數通過名稱打開文件

File fileName = new File("/Users/blad/Documents/CS2/Labs/Project01/input.txt"); 
     try { 
      Scanner sc = new Scanner(fileName); 
      while(sc.hasNextLine()){ 

       System.out.println(sc.nextLine()); 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

該文件的名稱是「input.txt」有沒有辦法解決這個問題?謝謝。

回答

0

你可以嘗試使用這些代碼一種不同的方法,看看這樣做是否能解決您的問題

FileReader fr = new FileReader("C:/Users/OCMEngineering1/Desktop/library/library/textfile/student.txt"); 
LineNumberReader lnr = new LineNumberReader(fr); 
0

試試這個 - 它會讀取文件名,然後用它來創建文件object.If你想用一個while循環讀多個文件名。

Scanner in = new Scanner(System.in); 
System.out.println("What is the filename?"); 
String input = in.nextLine(); 
File fileName = new File(input); 
+0

如何檢查我輸入的名稱是否存在?在文件夾項目 –

+0

中做isFile();如果文件存在,它會給你真 –

+0

例如 - 新的文件(「路徑/到/ file.txt」)。isFile(); –

相關問題