tags:

views:

27

answers:

2

Hi,

I am downloading a text-file from example.com/test.txt and I need the contents only during the runtime of my app, they don't need to be saved to a static file.

My code so far:

            InputStream input = new BufferedInputStream(getURL.openStream());
            OutputStream output = new FileOutputStream(tempFile);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();

How would I go about writing the online-file contents to a String rather than saving the file locally? I have tried appending data to a String in the while-statement, but just get garbled text (as expected, but I don't know what else to do). Convert byte back to String?

Thanks for your help!

+1  A: 

Instead of FileOutputStream use ByteArrayOutput stream. You then can invoke toString to convert it into a string.

        InputStream input = new BufferedInputStream(getURL.openStream());
        OutputStream output = new ByteArrayOutputStream();

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
        String result = output.toString();
Konstantin Burov
Works perfectly, thanks for the quick reply!
Nick
+1  A: 

You can use a method similar to that which is described here.

Code snippet from the Java docs:

URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();

You just need to append each line to a String instead of sending it to System.out.

Drew
String concatenation through + operator is not that effective. You'd better use StringBuilder.
Konstantin Burov
Works as well, thank you :-)!
Nick