We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Easy question: from InputStream to File (FileOutputStream)

NGInterface
NGInterface asked
on
Medium Priority
2,162 Views
Last Modified: 2010-08-05
Hi,
   Can anyone help with this problem:

I have an InputStream coming over from HttpClient (from an HTTP GET request), and wish to write the data coming in from the InputStream object to a file (say, "raw.xml"); I can't seem to find any information online on how to connect InputStream to FileOutputStream or something similar...

Any help will be appreciated!
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016

Commented:
method.getResponseAsStream()

and copy it
CERTIFIED EXPERT
Top Expert 2016

Commented:
Sorry, it's

method.getResponseBodyAsStream()
CERTIFIED EXPERT
Top Expert 2016

Commented:
You could also do

FileOutputStream out = new FileOutputStream("x.html");
out.write(method.getResponseBody());
out.close();

Author

Commented:
Oh, I mean, I already got method.getResponseBodyAsStream() -- I just don't know how to turn that into a file...the amount of information coming over HTTP is very large, so responseBody() may not be the right approach...
CERTIFIED EXPERT
Top Expert 2016
Commented:
FileOutputStream out = new FileOutputStream("x.html");
final int BUFFER_SIZE = 1 << 10 << 3; //8KiB buffer
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
InputStream in = method.getResponseBodyAsStream();
while ((bytesRead = in.read(buffer)) > -1) {
      out.write(buffer, 0, bytesRead);
}
in.close();
out.close();

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
> InputStream in = method.getResponseBodyAsStream();

better off using a buffered stream

InputStream in = new BufferedInputStream(method.getResponseBodyAsStream());
CERTIFIED EXPERT
Top Expert 2016

Commented:
:-)
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.