簡體   English   中英

Java程序有條件地從文件中讀取行

[英]java program to conditionally read lines from file

我是Java編程的新手。 我將這段代碼放在一起,以讀取以下文本文件中“開始”和“結束”標記之間的所有行。

開始

你好

你好

怎么樣

在干嘛

結束

我的程序如下。

package test;

import java.io.*;

public class ReadSecurities {
public static int countLines(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

      try {
        FileInputStream in = new FileInputStream("U:\\Read101.txt");
        FileOutputStream out = new FileOutputStream("U:\\write101.txt");
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

        for (int i=1; i<=countLines("U:\\Read101.txt"); i++) {
            String line=br.readLine();
                 while (line.contains("Start")) {
                    for (int j=i; j<=countLines("U:\\Read101.txt"); j++) {
                        String line2=br.readLine();
                        System.out.println(line2);
                        if(line2.contains("End")) break; 
                    else {
                             bw.write(line2);
                             bw.newLine();
                    }
                        bw.close();
                    } break;
                 }
               }
            br.close();
      }
      catch (Exception e) { }
      finally { }
      }
}

該程序僅讀取前兩行“嗨,你好”,好像if條件不存在。 我感覺到錯誤是很基本的,但是請糾正我。

String line;

do{ line = br.readLine(); }
while( null != line && !line.equals("Start"));

if ( line.equals("Start") ) { // in case of EOF before "Start" we have to skip the rest!
    do{ 
        line = br.readLine(); 
        if ( line.equals("End") ) break;
        // TODO write to other file
    }while(null != line )
}

應該那樣簡單。 為了簡潔起見,我省略了資源的創建/銷毀以及適當的異常處理。

但是請至少執行日志記錄異常

編輯:

如果開始之前遇到EOF,則必須跳過復制步驟!

您在代碼中犯了一個關鍵錯誤:您沒有正確處理異常。 兩件事情:

  1. 從不捕獲Exception 僅捕獲一種類型的異常,或者指定要捕獲的異常列表。 在您的情況下,一個簡單的IOException就足夠了。

  2. 切勿將捕獲塊留空。 拋出一個新異常,返回一個值,或者-在您的情況下,使用e.printStackTrace()打印該異常。

當您完成這兩件事時,您會注意到您的代碼拋出IOException ,因為您過早關閉bw -Stream。 bw.close()向下移至bw.close()所在的br.close()

現在,完成此操作后,您的代碼幾乎可以正常工作了。 唯一的事情是-您現在獲得NullPointerException 這是因為您不會在讀取所有條目后更改line 對此的簡單解決方案是從

while(line.equals("Start")) { ...

if(line.equals("Start")) { ...

另外,您的代碼中還有其他一些不太整潔的東西,但是我現在暫時不要說了-經驗是有時間的。

對於Java 8:

List<String> stopWords = Arrays.asList("Start", "End");
try (BufferedReader reader = new BufferedReader(input))) {
   List<String> lines = reader.lines()
     .map(String::trim)
     .filter(s -> !StringUtils.isEmpty(s) && !stopWords.contains(s))
     .collect(Collectors.toList());
}

暫無
暫無

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

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