1

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!

Nick
  • 3,504
  • 2
  • 39
  • 78

2 Answers2

1

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
  • 68,980
  • 16
  • 115
  • 93
1

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.

Community
  • 1
  • 1
Drew
  • 2,269
  • 21
  • 16