如何在写完后获取字符串?

时间:2016-01-28 10:46:55

标签: java

我有一些阅读内容和写作的逻辑。 在我发送给客户之前,我想删除一些内容

private void handGet(HttpServletRequest request, HttpServletResponse response, IFileStore file)
            throws IOException, CoreException, NoSuchAlgorithmException, JSONException {
        ....//set header
        OutputStream outputStream = response.getOutputStream();
        Writer out = new OutputStreamWriter(outputStream, "UTF-8");
        out.write(EOL);
        out.flush();
        IOUtilities.pipe(file.openInputStream(EFS.NONE, null), outputStream, true, false);
        out.write(EOL + "--" + boundary + EOL); //$NON-NLS-1$
        out.flush();

    }

public static void pipe(InputStream inputStream, OutputStream outputStream, boolean closeIn, boolean closeOut) throws IOException {
        byte[] buffer = new byte[4096];
        int read = 0;
        try {
            while ((read = inputStream.read(buffer)) != -1)
                outputStream.write(buffer, 0, read);
        } finally {
            if (closeIn)
                safeClose(inputStream);
            if (closeOut)
                safeClose(outputStream);
        }
    }

现在我想在out或outputStream中得到结果,并希望替换一些字符串,以便我可以获取数据然后如何保存它?

1 个答案:

答案 0 :(得分:1)

outputStream的替换可以这样做(将其放在pipe方法的try-block中):

            // This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement string.
            String str = new String(buffer, Charset.forName("UTF-8"));
            // Replaces each occurence of "replaceThis" with "", for regex use: replaceAll(String regex, String replacement)
            str = str.replace("replaceThis", "");
            // This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement byte array
            byte[] replaced = str.getBytes(Charset.forName("UTF-8"));
            while ((read = inputStream.read(buffer)) != -1)
                outputStream.write(replaced);

这是使用UTF-8字符集,只要它可用。不过,我不知道性能。

我不确定OutputStreamWriter的用途是什么,但您可以使用write(String str, int off, int len)方法将String写入其中