java从用户输入中查找/读取文件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19626468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Have java find/read a file from user input?
提问by WeekzGod
The program must print the text in file I ask it to read. The problem is I coded it to read the text from a specific file
该程序必须打印我要求它阅读的文件中的文本。问题是我将它编码为从特定文件中读取文本
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
How do I get the program to read the text from a file specified by user input? *The file is going to be in the same directory/folder as the program so that's not an issue.
如何让程序从用户输入指定的文件中读取文本?*该文件将与程序位于同一目录/文件夹中,因此这不是问题。
EDIT: My prior attempt at user input
编辑:我之前对用户输入的尝试
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
回答by nhgrif
Declare a String
variable, such as someUserFile
, take user input. Then...
声明一个String
变量,例如someUserFile
,接受用户输入。然后...
File file = new File(someUserFile);
Scanner inputFile = new Scanner(file);
You may want to check their input and append ".txt"
to the end of their input.
您可能想要检查他们的输入并附".txt"
加到他们输入的末尾。
If this works:
如果这有效:
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
Then this:
然后这个:
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Will do the exact same thing assuming you type numbersonnumbers.txt
and type that exactly.
假设您键入numbersonnumbers.txt
并准确键入,将执行完全相同的操作。
Assuming you type numbersonnumbers.txt
exactly, the second snippet does the EXACT same thing as the first snippet.
假设您输入numbersonnumbers.txt
准确,第二个代码段与第一个代码段执行完全相同的操作。
回答by ryanlutgen
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
回答by CodingBird
Firstly you should ask the user the input the filename. Then just replace the "numbersonnumbers.txt" in your code to the variable that you set for the user input.
首先,您应该要求用户输入文件名。然后只需将代码中的“numbersonnumbers.txt”替换为您为用户输入设置的变量。
Scanner in = new Scanner(System.in);
System.out.println("What is the filename?");
String input = in.nextLine();
File file = new File(input);
回答by James Stowell
1)The program must print the text in file:
1)程序必须打印文件中的文本:
Lets call this file, dataFile.text, or dataFile.dat(either way works)
Assuming that the client will be inputing any file, we must get the file's name...
These Java statements will do the trick:
// Create a Scanner to read user's file name
Scanner userInput = new Scanner(System.in);
// Request the file name from client
System.out.println("Enter name of input file: ");
// Gets client's file name
String fileName = scanFile.nextLine();
// scanFile, scans the new File fileName (client's file), which is located in the src directory. The "src/" represents the path to the file (client's file).
Scanner scanFile = new Scanner(new File("src/" + fileName));
- Since the problem states the file, "will be located in the same directory as the program," its not an issue.
让我们调用这个文件,dataFile.text或dataFile.dat(无论哪种方式都有效)
假设客户端将输入任何文件,我们必须获取文件名...
这些 Java 语句可以解决问题:
// 创建一个扫描器来读取用户的文件名
Scanner userInput = new Scanner(System.in);
// 从客户端请求文件名
System.out.println("请输入输入文件名:");
// 获取客户端的文件名
String fileName = scanFile.nextLine();
// scanFile,扫描位于src目录下的新文件fileName(客户端的文件)。“src/”表示文件(客户端文件)的路径。
Scanner scanFile = new Scanner(new File("src/" + fileName));
- 由于问题指出文件“将位于与程序相同的目录中”,因此这不是问题。
---------------------------------------------------------------------------------
-------------------------------------------------- -------------------------------
2)The problem is I coded it to read the text from a specific file
2)问题是我编码它以从特定文件中读取文本
Yes, all you did was create file of your own called, "numbersonnumbers.txt," this is exactly the code you should be following in the solution to this problem, but instead of typing "numbersonnumbers.text", you will be using the client's input file, which is the String variable "fileName" in the previous code...*
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
是的,您所做的只是创建您自己的名为“numbersonnumbers.txt”的文件,这正是您在解决此问题时应该遵循的代码,但您将使用客户端的输入文件,也就是前面代码中的字符串变量“fileName”...*
File file = new File("numbersonnumbers.txt");
扫描仪输入文件 = 新扫描仪(文件);
Corrected: File file = new File("src/" + fileName);
更正: File file = new File("src/" + fileName);
Scanner inputFile = new Scanner(file); // Will scan all the file's data
扫描仪输入文件 = 新扫描仪(文件);// 将扫描所有文件的数据
Corrected More: Scanner inputFile = new Scanner(new File("src/" + fileName));
更正更多:Scanner inputFile = new Scanner(new File("src/" + fileName));
---------------------------------------------------------------------------------
-------------------------------------------------- -------------------------------
3)The program must print the text in file
3)程序必须打印文件中的文本
- Now to print the data items in the file to the console you simply, copy every item in the file, to an array, list, or tree depending on specifications of implementation, but this is obviously begininer programming so, never mind lists and trees, use an array.
- 现在要将文件中的数据项打印到控制台,您只需根据实现规范将文件中的每个项复制到数组、列表或树中,但这显然是初学者编程,因此,不要介意列表和树,使用数组。
So you have completed upto either Scanner scanFile in #1 or Scanner inputFile in #2
所以你已经完成了 #1 中的 Scanner scanFile 或 #2 中的 Scanner inputFile
Now, create an array, obviously the type of array would be based on the type of data items in the file... Strings for (e.g., month names) or int for (e.g., ID numbers .. ect)
现在,创建一个数组,显然数组的类型将基于文件中数据项的类型... Strings for(例如,月份名称)或 int for(例如,ID 号码等)
Assuming the data items in the file are names of months (jan, feb, march) we will make an array of type String.
假设文件中的数据项是月份名称(一月、二月、三月),我们将创建一个字符串类型的数组。
String[] fileData = new String[100];// has random length (100)
字符串[] 文件数据 = 新字符串[100]; // 具有随机长度 (100)
// Now we will be copying every item from the file into the array, you will need place holder value to keep track of the position during the traversal (stopping at every item) of the file's items.
// 现在我们将把文件中的每个项目复制到数组中,您将需要占位符值来跟踪文件项目的遍历(在每个项目处停止)期间的位置。
int i = 0;// itialize the start of the traversal (index 0 of the file items)
int i = 0; // 初始化遍历的开始(文件项的索引 0)
while (scanFile.hasNextLine()) {// While file has input on next line, read from file.
while (scanFile.hasNextLine()) {// 当文件在下一行有输入时,从文件中读取。
fileData[++i] = scanFile.nextLine(); // Input file data and increment i
System.out.println(fileData[i]); // Prints all of the file's data items
} // end while
Respectfully, -!di0m
恭敬地,-!di0m
回答by Fouad Boukredine
You got almost everything you need in your code already. You just need to re-arrange your lines of code properly, and add couple more.
你已经在你的代码中获得了几乎所有你需要的东西。您只需要正确地重新排列代码行,并添加更多代码。
you need two steps: scan what the user enters as full file path, then scan the actual file data as follows:
您需要两个步骤:扫描用户输入的完整文件路径,然后扫描实际文件数据如下:
// Scanner Object to be used for the user file path input
Scanner keyboard = new Scanner(System.in);
// Asks the user to enter the full path of their file
System.out.print("Enter your full file path: ");
// Stores the user input file path as a string
String filename = keyboard.nextLine();
// Creates a File object for the file path, and scans it
Scanner inputFile = new Scanner(new File(filename);
Now you can read the scanned File inputFile
. For example you can use a while
loop to read one line at a time to read all data and print it out as follows:
现在您可以阅读扫描的 File inputFile
。例如,您可以使用while
循环一次读取一行来读取所有数据并将其打印出来,如下所示:
// Reads one line at a time, and prints it out
while(inputFile.hasNext) {
System.out.println(inputFile.nextLine());
Or you can put each line's raw data (trimmed and split) in an array and print out each line as an array as follows:
或者您可以将每一行的原始数据(修剪和拆分)放入一个数组中,并将每一行作为数组打印出来,如下所示:
// Declares a String array[] to be used for each line
String[] rawData;
// Reads one line at a time, trims and split the raw data,
// and fills up the array with raw data elements, then prints
// out the array. it repeats the same thing for each line.
while (scanner2.hasNext()) {
rawData = scanner2.nextLine().trim().split("\s+");
System.out.println(Arrays.toString(rawData));
}