从使用BufferedReader获取文件更改为String

时间:2014-12-06 22:49:35

标签: java inputstream 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和Reader ...但是如果它的其中一个似乎无法取得进展。

1 个答案:

答案 0 :(得分: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");
    }
}