3

How to read file stored on server using java? I have .txt file stored on server, how to read contents of it.

String test, newq;

newq = "http://www.example.com/pqr.txt";

test = new String(Files.readAllBytes(Paths.get(newq)));

// variable test should contain pqr.txt content

What I am doing wrong?

  • 2
    I dont want to download the file, just want to read it! –  Feb 24 '15 at 10:25
  • Sorry, maybe I didn't understand your question. Do you want to run this code on server itself? Or do you want to access file from client (your local machine)? – default locale Feb 24 '15 at 10:26
  • Access from client; I want client to just read the text, string in it. –  Feb 24 '15 at 10:27
  • `new String(Files.readAllBytes(Paths.get(newq)))` <-- don't do that. Specify the encoding. – fge Feb 24 '15 at 10:30
  • To download a file you need first to read it, then to store it. Please, read answers in the linked question. You can apply them directly to your problem, you don't have to store file after reading it. – default locale Feb 24 '15 at 10:31

2 Answers2

4

That code works fine for files found in the file system. Path object is designed specifically for this.

When you want to access a remote file, it no longer works.

One easy way to read the file is this:

    URL url = new URL("https://wordpress.org/plugins/about/readme.txt");
    String text = new Scanner( url.openStream() ).useDelimiter("\\A").next();

It is not very pretty but it is small, it works and does not require any library.

With Apache Commons you can do it like this:

   URL url = new URL("https://wordpress.org/plugins/about/readme.txt");
   String text = IOUtils.toString(url.openStream());
Cristian Sevescu
  • 1,364
  • 8
  • 11
1

Go through an HttpURLConnection and use a StringBuilder. Sketch code:

final URL url = new URL("http://www.example.com/pqr.txt");

final StringBuilder sb = new StringBuilder();

final char[] buf = new char[4096];

final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
    .onMalformedInput(CodingErrorAction.REPORT);

try (
    final InputStream in = url.openStream();
    final InputStreamReader reader = new InputStreamReader(in, decoder);
) {
    int nrChars;
    while ((nrChars = reader.read(buf)) != -1)
        sb.append(buf, 0, nrChars);
}

final String test = sb.toString();
fge
  • 119,121
  • 33
  • 254
  • 329
  • I'm looking at the source code of `HttpURLConnection `, `HttpURLConnection` is an abstract class, how you created an object? used any other API ? – Saravana Feb 24 '15 at 10:53
  • Sorry, error from my part. See the amended code – fge Feb 24 '15 at 11:25