2014-12-06 15 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

相关问题