2014-12-06 49 views
0

我有一個工作的應用程序,將採取文本文件,修改它的階段,直到它是整潔和可用。 每個階段都會帶入一個文件並對其進行修改,然後吐出一個文件,以便下一個文件緩衝。從使用BufferedReader的文件更改爲字符串

我想讓它更清潔,所以我想停止拉動文件,除了第一個,以及以字符串的形式將輸出傳遞給應用程序。 使用此代碼,我該怎麼做?

這是第二階段。

try { 
       BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("C:/Stage_Two.txt"))); 
       StringBuffer stringBuffer = new StringBuffer(); 
       String line; 
       while ((line = bufferedReader.readLine()) != null) { 
        Pattern pattern = Pattern.compile("ALL|MESSAGE|Time|PAPER_MAIN|GSP"); 
        if (pattern.matcher(line).find()) { 
         continue; 
        } 
        stringBuffer.append(line); 
        stringBuffer.append("\n"); 
       } 
       BufferedWriter bwr = new BufferedWriter(new FileWriter(new File("C:/Stage_Three.txt"))); 
       bwr.write(stringBuffer.toString()); 
       bwr.flush(); 
       bwr.close(); 
       // to see in console 
       //System.out.println(stringBuffer); 
      } catch (IOException e) { 
      } 

我已經調查的InputStream,InputStreamReader的,和讀者......但如果這些我似乎無法取得進展的其一。

+0

你只是在尋找代碼審查? – 2014-12-06 23:00:08

+0

不,這是從拉入文件變爲使用字符串的方向。 – 2014-12-06 23:01:19

+0

閱讀有關* decorator模式*的內容。考慮讓一個與這些「修飾符類」不相關的不同組件關注閱讀和/或打擊文件。 – Tom 2014-12-06 23:03:08

回答

0

我不確定字符串如何清理它。使用讀者和作者的好處是你不需要在內存中擁有一切。以下代碼將允許處理非常大的文件。

public void transformFile(File in, File out) throws IOException { 

    /* 
    * This method allocates the resources needed to perform the operation 
    * and releases them once the operation is done. This mechanism is know 
    * as a try-with-resource. After the try statement exits, the resources 
    * are closed 
    */ 

    try (BufferedReader bin = new BufferedReader(new FileReader(in)); 
      Writer bout = new FileWriter(out)) { 

     transformBufferedReader(bin, bout); 
    } 
} 

private void transformBufferedReader(BufferedReader in, Writer out) throws IOException { 
    /* 
    * This method iterates over the lines in the reader and figures out if 
    * it should be written to the file 
    */ 

    String line = null; 
    while ((line = in.readLine()) != null) { 
     if (isWriteLine(line)) writeLine(line, out); 
    } 
} 

private boolean isWriteLine(String line) throws IOException { 

    /* 
    * This tests if the line should be written 
    */ 

    return !line.matches("ALL|MESSAGE|Time|PAPER_MAIN|GSP"); 
} 

private void writeLine(String line, Writer writer) throws IOException { 

    /* 
    * Write a line out to the writer 
    */ 

    writer.append(line); 
    writer.append('\n'); 
} 

如果你堅持使用字符串,你可以添加下面的方法。

public String transformString(String str) { 
    try (BufferedReader bin = new BufferedReader(new StringReader(str)); 
      Writer bout = new StringWriter()) { 

     transformBufferedReader(bin, bout); 
     return bout.toString(); 
    } catch (IOException e) { 
     throw new IllegalStateException("the string readers shouln't be throwing IOExceptions"); 
    } 
} 
+0

我喜歡它Isaiah! – 2014-12-07 13:34:04

相關問題