从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...)
}
谢谢!