簡體   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