簡體   English   中英

從文件逐行讀取Java不能正確讀取行

[英]Java read from file line by line not reading lines correctly

我已經用以下格式在文本文件中保存了很多推文:

Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: #Brazil on track to becoming the leader of #wind #energy production in Latin America http://t.co/MFJjNPxodf
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: @ConceptOfficial FOLLOW ME GUYS PLEASE I LOVE YOU SO MUCH 💕BRAZIL LOVE YOU💙💚💛x16
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: @JamesFenn90 plenty teams travelled far more in Brazil from their bases to each game.I'm sure eng can manage a trip to Amsterdam etc etc

現在,我要做的是從文本文件中逐行讀取內容,然后通過"TweetTextExtract: "分割行,但是由於某種原因,我不斷收到ArrayIndexOutOfBoundsException:1錯誤,我看不到為什么每行都有"TweetTextExtract: "一詞。 這是控制台中的錯誤:

Country:Brazil_result.txt Date: \r\n09/19/14 @ConceptOfficial FOLLOW ME GUYS 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at WhatToThink.main(WhatToThink.java:28)

帶有此tweet的行具有"TweetTextExtract: "術語,其后一行也是如此。 我不確定為什么會這樣。 這是代碼:

String folderPath = "C:/Users/me/workspace/Sentiment Analysis/Good Data";

        File fin = new File(folderPath + "/Brazil_result" + ".txt");
        FileInputStream fis = new FileInputStream(fin);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));

        String line = null;
        while ((line = br.readLine()) != null) {
            String[] stringline = line.split("TweetTextExtract: ");
            System.out.println(stringline[0] + stringline[1]);
            //System.out.println(line);
        }

        br.close();

當我運行它時,它實際上並沒有為我提供例外。但是,如何通過在拆分的String中動態打印元素來避免此錯誤,以下增強循環將為您提供相同的結果。

String[] stringline = line.split("TweetTextExtract: ");
for (String s : stringline) {
            System.out.print(s);
} 
System.out.println("");

通過查看結果,您可以發現自己在弦線數組中存在多少元素。

您的問題幾乎肯定是文件的文本編碼錯誤。 將文件另存為UTF-8(或UTF-16),然后使用

new InputStreamReader(fis, "UTF-8") //or UTF-16

如果您在上述構造函數中使用的編碼與文本文件中的編碼不匹配,則會出現亂碼,即使在第一行也無法進行split

如果要保留文本文件的原始編碼,只需找出它的含義並使用它即可。

您可以使用類似這樣的內容:

if (line.contains("TweetTextExtract: ")){
     String[] stringline = line.split("TweetTextExtract: ");
     System.out.println(stringline[0] + stringline[1]);
}
else{
     System.out.println("Line doesn't't contain \"TweetTextExtract: \"");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM