有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    替换outputStream可以这样做(把它放在pipe方法的try块中):

                // 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)方法将字符串写入它