I 开发者_如何学Gohave a file as https://localhost/myeg.xml I want to read the file as string in Java. Can somebody help me if there is a separate library or any way else.
You can try:
URL url = new URL(myfile);
InputStream is = url.openStream();
byte[] buf = new byte[1024];
int read = -1;
StringBuilder bld = new StringBuilder();
while ((read = is.read(buf, 0, buf.length) != -1) {
bld.append(new String(buf, 0, read, "utf-8"));
}
String s = bld.toString();
- This assumes
utf-8
, if the originating host does specify encoding, I would use.openConnection()
and figure out the "content type" (and encoding) before reading the stream. - For performance you may want to wrap the
InputStream
in aBufferedInputStream
. - You probably want a
try-finally
to close theInputStream
common-io:
URL url = new URL("https://etc..");
InputStream input = url.openStream();
String str = IOUtils.toString(input, "utf-8"); //encoding is important
input.close(); // this is simplified - resource handling includes try//finally
Or see examples in the official tutorial.
You could use Commons HTTP Client. See this example!
精彩评论