1

I have 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.

3 Answers 3

8

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 a BufferedInputStream.
  • You probably want a try-finally to close the InputStream
Sign up to request clarification or add additional context in comments.

1 Comment

that's an InputStream. he said he wants String. Finish the example ;)
4

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.

Comments

2

You could use Commons HTTP Client. See this example!

2 Comments

Wait 'till you discover you need authentication and header manipulation to get the file! ;)
one by one. you can't throw everything at somebody that doesn't know much about the subject

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.