【问题标题】:Using the same Scanner in java在 java 中使用相同的 Scanner
【发布时间】:2016-10-13 09:19:30
【问题描述】:

我是否可以使用扫描器从用户那里读取以输入某个输入,然后创建一个新实例以从文件中读取?

Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
sc = new Scanner(fileName);

displayAll(sc); //a static void method that takes the Scanner object as a parameter and is supposed to read and display the input stored in the .txt file

【问题讨论】:

  • 是的,你可以。你为什么不试试呢?
  • 只需使用if,找到匹配后,重新初始化扫描仪
  • @PavneetSingh 他有一个工作代码。如果文件名是带有扩展名的文件的路径,它将起作用
  • @xenteros OP 说user to enter a certain input 然后create a new instance of it to read from a file

标签: java java.util.scanner filereader


【解决方案1】:

好吧,你需要使用File

Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
sc = new Scanner(new File(fileName));

try-catch 不存在的文件会更安全。您可以使用if-else。嗯......逻辑取决于你。也许是这样的:

Scanner sc = new Scanner(System.in);
while (true) {
    System.out.println("Enter file name");
    String filename = sc.next();
    if (!filename.startsWith("sth")) {    //this will reask if the file name doesn't start with "sth"
        continue;
    try {
        Scanner s = sc; //just in case you never gonna use System.in
        sc = new Scanner(new File(filename));
        s.close(); //just in case you're sure you never gonna use System.in
        break;
    } catch (Exception e) {
        System.out.println("Wrong filename - try again");
    }
}

显然,您可以将if 条件更改为您喜欢的任何内容。我只是想给你一个更广阔的视野。如果您愿意,可以切换到equals

【讨论】:

  • 好像你也没有看我的评论,OP不要这个,只需添加一个if条件以满足OP要求
  • @PavneetSingh 是的,添加了。小姐输入了答案的测试版。对不起m8
  • 如果文件存在,我将在循环之前添加一个Scanner tmp = sc; 以关闭 System.in 的扫描程序。如果没有,此实例将保持打开状态
  • 关闭在 System.in 上打开的 Scanner 也会关闭 System.in 本身,您以后将无法在 System.in 上重新打开另一个 Scanner。
  • @KlitosKyriacou 你是对的。我快速应用了更改
【解决方案2】:

您使用的 Scanner 与问题标题中所述不同。您正在创建 Scanner 的两个不同且独立的实例。

sc 在您的代码中是一个扫描仪参考。首先,它引用第一个Scanner 对象。然后将对象引用更改为指向第二个Scanner 对象。您不是在重用 Scanner 对象,而是在重用对象引用。这完全没问题。

创建Scanner 对象时,无法更改扫描仪使用的源。从不同来源获取数据需要创建一个新实例。

在您的代码示例中,您为System.in 和一个文件使用两个不同的扫描器的方法很好。但是,您的示例中的问题是您为文件 Scanner 使用了错误的构造函数。要使用文件作为源来创建 Scanner,您需要创建一个 FilePath 对象,并将此对象用作构造函数参数而不是文件名字符串:

new Scanner(new File(filename));

或者:

new Scanner(Paths.get(filename));

【讨论】:

  • 您对 instanceS 的看法是正确的,但还有其他解决方案吗?你能改变现有实例的流吗?这应该在你的答案中回答;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多