简体   繁体   English

Java从命令行参数读取并打印文件

[英]Java read a file and print it, from command line arguments

Accept command line argument for a string to open a text file and print its contents. 接受命令行参数输入字符串以打开文本文件并打印其内容。 Text file is like a dictionary: a list of words separated by new lines. 文本文件就像一个字典:用换行符分隔的单词列表。

Using other examples this is what I've tried to no success. 使用其他示例,这是我尝试未成功的示例。 Do not use any java collections/libraries outside these ones. 不要在这些之外使用任何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();
}
}
}

Unless your file contains int(s), calling sc.nextInt() is not correct; 除非您的文件包含int,否则调用sc.nextInt()是不正确的。 and when it is correct, you would want to use sc.hasNextInt() (not sc.hasNextLine() ). 正确时,您将要使用sc.hasNextInt() (而不是sc.hasNextLine() )。 Here, you want to use sc.nextLine() to read each word (since there is one per line). 在这里,您想使用sc.nextLine()读取每个单词(因为每行一个)。 Also, you should check that the file exists before attempting to read from it (so you can handle that condition reasonably). 另外,在尝试读取文件之前,应检查文件是否存在(以便可以合理地处理该情况)。 Finally, I would prefer try-with-Resources over explicitly managing the life-cycle of your Scanner . 最后,相对于显式管理Scanner的生命周期,我更喜欢try-with-Resources Like, 喜欢,

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM