【问题标题】:Java read a file and print it, from command line argumentsJava 从命令行参数读取文件并打印它
【发布时间】:2020-01-16 20:21:07
【问题描述】:

接受字符串的命令行参数以打开文本文件并打印其内容。 文本文件就像一本字典:由换行符分隔的单词列表。

使用其他示例,这是我尝试但没有成功的方法。不要使用这些之外的任何 java 集合/库。

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class test{
public static void main(String[] args) {
  File file = new File(args[0]);
   try {    
        Scanner sc = new Scanner(file);
        while (sc.hasNextLine()) {
            int i = sc.nextInt();
            System.out.println(i);
        }
        sc.close();
    }
   catch (FileNotFoundException e) {
        e.printStackTrace();
}
}
}

【问题讨论】:

  • 欢迎来到 SO。你有什么问题?
  • int i = sc.nextInt(); 基于 “文本文件就像字典:由换行符分隔的单词列表。” 不确定这是做什么用的。 似乎会导致问题

标签: java file io


【解决方案1】:

除非您的文件包含 int(s),否则调用 sc.nextInt() 是不正确的;如果它是正确的,你会想要使用sc.hasNextInt()(而不是sc.hasNextLine())。在这里,您想使用sc.nextLine() 来读取每个单词(因为每行一个单词)。此外,您应该在尝试读取文件之前检查该文件是否存在(这样您就可以合理地处理这种情况)。最后,我更喜欢try-with-Resources,而不是明确管理Scanner 的生命周期。喜欢,

File file = new File(args[0]);
if (!file.exists()) {
    try {
        System.err.printf("Could not find '%s'.%n", file.getCanonicalPath());
        System.exit(1);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
try (Scanner sc = new Scanner(file)) {
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        System.out.println(line);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    相关资源
    最近更新 更多