如何使用Scanner在java中提示用户输入文件?

时间:2022-10-24 21:54:51

I need to know how to prompt user for a file and then be able to use the file in my program. Here is my unsuccessful attempt.

我需要知道如何提示用户输入文件,然后才能在我的程序中使用该文件。这是我不成功的尝试。

public static void main(String[] args) {
Scanner Scanscan = new Scanner(System.in);
System.out.print("Input filename:");
String filename = Scanscan.nextLine();
File inputFile = new File(filename);
Scanner reader = new Scanner(inputFile);

I get a "File not found exception" when I try it.

我尝试时得到“文件未找到异常”。

2 个解决方案

#1


2  

You get a FileNotFoundException because the filename the user entered doesn't exist in the system. Enter a filename that does exist, and it should work. Make sure the file you're getting is in the directory you're running the program from. Try entering the name of the java file you're working on amd see if it works.

您收到FileNotFoundException,因为用户输入的文件名在系统中不存在。输入确实存在的文件名,它应该有效。确保您获得的文件位于您运行该程序的目录中。尝试输入您正在处理的java文件的名称,看看它是否有效。

#2


1  

File does not exist. You should,

文件不存在。你应该,

1.Check that your file is existed corresponding to your executing application.

1.检查您的文件是否与您正在执行的应用程序相对应。

2.Try to provide full hard path of file in your system like "C:\\sample.txt"

2.尝试在系统中提供完整的文件硬路径,如“C:\\ sample.txt”

#1


2  

You get a FileNotFoundException because the filename the user entered doesn't exist in the system. Enter a filename that does exist, and it should work. Make sure the file you're getting is in the directory you're running the program from. Try entering the name of the java file you're working on amd see if it works.

您收到FileNotFoundException,因为用户输入的文件名在系统中不存在。输入确实存在的文件名,它应该有效。确保您获得的文件位于您运行该程序的目录中。尝试输入您正在处理的java文件的名称,看看它是否有效。

#2


1  

File does not exist. You should,

文件不存在。你应该,

1.Check that your file is existed corresponding to your executing application.

1.检查您的文件是否与您正在执行的应用程序相对应。

2.Try to provide full hard path of file in your system like "C:\\sample.txt"

2.尝试在系统中提供完整的文件硬路径,如“C:\\ sample.txt”