0

在不丢失编码/字符集的情况下,从 OutputStream(url.openStream())写入 Writer(可以是 FileWriter 或 Stringwriter)的正确方法是什么?

public static String parseURLContentIntoFile(final URL url, final File fileToFill) throws IOException{      
    return parseURLContentIntoOutputWriter(url, new OutputStreamWriter(FileUtils.openOutputStream(fileToFill),"UTF-8"));        
}

public static String parseURLContentIntoString(final URL url) throws IOException{
    final StringWriter output = new StringWriter(); // Or StringBuilderWriter
    parseURLContentIntoOutputWriter(url, output);
    return output.getBuffer().toString();   //Or output.getBuilder().toString()
}


private static String parseURLContentIntoOutputWriter(final URL url, final Writer writer) throws IOException{

    InputStreamReader in = null;
    BufferedWriter out = null;
    try {
        out = new BufferedWriter(writer);
        in = new InputStreamReader(url.openStream(),"UTF-8");
        for(String line : IOUtils.readLines(in)){ //Uses a buffer internally
                      (...VERY LONG parsing...)
          if (!line.isEmpty()) IOUtils.write(line,out); 
        }
        (...Exception handling and stream closing...)
 }

谢谢!

4

0 回答 0