2016-03-01 25 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(); –