繁体   English   中英

从文本文件Java读取行?

[英]Read line from text file Java?

所以我是Java的新手,我正在尝试的一切都没有用。 有很多不同的方法可以从文件中读取,所以我想知道最简单的方法。 基本上,它是一个疯狂的Libs应用程序。 一种方法。 我一直试图成功运行它,我在file.close()函数上收到错误。 如果我拿走它,我会收到FileNotFoundException errors 所以我有点迷茫。 我应该改变什么?

public static void main(String[] args) throws Exception {
    String[] nouns = new String[4];
    String[] verbs = new String[6];
    String[] adjectives = new String[7];
    Scanner s = new Scanner(System.in);
    System.out.println("Please input 4 nouns, press \"Enter\" after each input.");
    for(int i=0; i<4; i++){
        nouns[i] = s.next();
    }
    System.out.println("Please input 6 verbs, press \"Enter\" after each input.");
    for(int i=0; i<6; i++){
        verbs[i] = s.next();
    }
    System.out.println("Please input 7 adjectives, press \"Enter\" after each input.");
    for(int i=0; i<7; i++){
        adjectives[i] = s.next();
    }
    File file = null;
    FileReader fr = null;
    LineNumberReader lnr = null;

    try {
        file = new File("H:\\10GraceK\\AP Computer Science\\Classwork\\src\\madlib.txt");
        fr = new FileReader(file);           
        lnr = new LineNumberReader(fr);
        String line = "";           
        while ((line = lnr.readLine()) != null) {
            System.out.println(line);               
        }
    } finally {
        if (fr != null) {
            fr.close();
        }
        if (lnr != null) {
            lnr.close();
        }
    }
}

好的,我修复了异常。 现在文件中的文本读取了动词[0]和类似的东西,但它实际上输出了动词[0],而不是数组中的单词。 如何将数组中的字符串附加到读取的字符串?

对于File ,方法close是未定义的。 请改用FileReader.close 更换

file.close();

fr.close();

事实上,关闭LineNumberReader就足够了,因为这将关闭底层的FileReader 您可以将close放在finally块中。 看这个例子

一如既往,我必须在阅读文件和流时推荐commons-io

尝试使用例如:

IOUtils.readLines

代码中的错误是@Reimeus提到的缺失方法。

Scanner API改进了并且变得更容易:

try {
    Scanner sc = new Scanner(new File("text.txt"));
    sc.useDelimiter(System.getProperty("line.separator"));
    String ln = sc.next();

} catch (FileNotFoundException ex) {
    Logger.getLogger(this.class.getName()).log(Level.SEVERE, null, ex);
}

暂无
暂无

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

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