Java通过命令行参数

时间:2019-09-16 01:15:28

标签: java file io

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

使用其他示例,这是我尝试未成功的示例。请勿在这些集合/库之外使用任何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();
}
}
}

1 个答案:

答案 0 :(得分:0)

除非文件中包含int,否则调用sc.nextInt()是不正确的;正确时,您将要使用sc.hasNextInt()(而不是sc.hasNextLine())。在这里,您想使用sc.nextLine()来读取每个单词(因为每行一个单词)。另外,在尝试读取文件之前,应检查文件是否存在(以便可以合理地处理该情况)。最后,相对于显式管理Scanner的生命周期,我更喜欢try-with-Resources。喜欢,

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();
}
相关问题