0

Consider the following.

val br = new BufferedReader(new FileReader(inputFileName))

But instead of a file, I want to read a file directly from the web, that is, from ftp or http. So, what would be the equivalent for reading from a URL?

pythonic
  • 20,589
  • 43
  • 136
  • 219

2 Answers2

4

It's URLConnection.

Here's an example from Java documentation : Reading from and Writing to a URLConnection :

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}
Mickael
  • 4,458
  • 2
  • 28
  • 40
1

you can use java.io.InputStream

import java.net.; import java.io.;

public class URLConnectionReader { 
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    } 
} 

for more info see Reading Directly from a URL

humazed
  • 74,687
  • 32
  • 99
  • 138