gpt4 book ai didi

java - 用户输入他们想要读入的文件名是什么?

转载 作者:行者123 更新时间:2023-12-01 11:55:40 27 4
gpt4 key购买 nike

出于此类任务的目的,我们被要求制作一个使用文件类的程序(我知道输入流要好得多),但是,是的,我们必须要求用户输入 .txt 的名称文件。

public class input {

public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
String name;
int lineCount = 0;
int wordCount = 0;


System.out.println("Please type the file you want to read in: ");
name = s.next();

File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);

我怎样才能得到

 File input = new File(...); 

搜索文件,因为仅输入“lab1task3”是行不通的。

编辑:错误-

 Exception in thread "main" java.io.FileNotFoundException: \lab1task3.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at inputoutput.input.main(input.java:19)

最佳答案

扫描仪无法以这种方式读取文件,您需要先将其存储为文件!如果将其放在 try-catch block 内,则可以确保在找不到文件时程序不会中断。我建议将其包装在 do-while/while 循环中(取决于结构),最终条件是找到文件。

我将您的主要方法更改为此并且它可以正确编译:

public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner (System.in);

System.out.println("Please type the file you want to read in: ");
String fname = sc.nextLine();

File file = new File (fname);
sc.close();
}

关于java - 用户输入他们想要读入的文件名是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28460563/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com