Use an URL instead of File for any access that is not on your local computer.

URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner s = new Scanner(url.openStream());

Actually, URL is even more generally useful, also for local access (use a file: URL), jar files, and about everything that one can retrieve somehow.

The way above interprets the file in your platforms default encoding. If you want to use the encoding indicated by the server instead, you have to use a URLConnection and parse it's content type, like indicated in the answers to this question.


About your Error, make sure your file compiles without any errors - you need to handle the exceptions. Click the red messages given by your IDE, it should show you a recommendation how to fix it. Do not start a program which does not compile (even if the IDE allows this).

Here with some sample exception-handling:

try {
   URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
   Scanner s = new Scanner(url.openStream());
   // read from your scanner
}
catch(IOException ex) {
   // there was some connection problem, or the file did not exist on the server,
   // or your URL was not in the right format.
   // think about what to do now, and put it here.
   ex.printStackTrace(); // for now, simply output it.
}
Answer from Paŭlo Ebermann on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › networking › urls › readingURL.html
Reading Directly from a URL (The Java™ Tutorials > Custom Networking > Working with URLs)
The following small Java program uses openStream() to get an input stream on the URL http://www.oracle.com/. It then opens a BufferedReader on the input stream and reads from the BufferedReader thereby reading from the URL.
🌐
Baeldung
baeldung.com › home › java › java io › download a file from an url in java
Download a File From an URL in Java | Baeldung
January 8, 2024 - We can use the Files.copy() method to read all the bytes from an InputStream and copy them to a local file: InputStream in = new URL(FILE_URL).openStream(); Files.copy(in, Paths.get(FILE_NAME), StandardCopyOption.REPLACE_EXISTING);
🌐
CodeSpeedy
codespeedy.com › home › how to read file from url in java?
How To Read File From URL In Java? - CodeSpeedy
July 31, 2018 - The path of the file in this example is http://domain.com/file.txt and we have passed it into the object of URL class. After that, we read it using BufferedReader class.
🌐
Net Informations
net-informations.com › java › net › readurl.htm
Reading Content in Java from URL
Read the text, using readLine() API method of BufferedReader. import java.net.*; import java.io.*; public class TestClass { public static void main(String[] args) throws Exception { try{ URL url = new URL("https://net-informations.com/"); BufferedReader reader = new BufferedReader( new ...
🌐
Alvin Alexander
alvinalexander.com › blog › post › java › how-open-read-url-java-url-class-example-code
How to open and read from a URL in Java (with just the URL class) | alvinalexander.com
Just create a new URL object, read data from the URL using the openStream method, wrap it in an InputStreamReader and BufferedReader, and loop through the output.
🌐
codippa
codippa.com › home › download file from url in java
Java - Download file from a URL in 3 ways
January 12, 2025 - These classes can be used to read a file using input stream and write its contents to an output stream. This approach is based on the following steps. Create a connection to the given file url. Get input stream from the connection.
🌐
Baeldung
baeldung.com › home › java › java io › how to read a file in java
How to Read a File in Java | Baeldung
January 8, 2024 - Here we used the URL and URLConnection class available in the standard SDK. To read a file which is located inside a JAR file, we will need a JAR with a file inside it. For our example, we will read “LICENSE.txt” from the “hamcrest-library-1.3.jar” file:
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 27624740 › java-reading-file-txt-from-url
Java reading file txt from URL - Stack Overflow
I used this code : BufferedReader reader = new BufferedReader(new InputStreamReader((new URL("MY TXT URL")).openStream())); String line = reader.readLine(); int k =0; String[] SaveLine = new String[20]; for( k = 0; line!=null; k++) { ...
🌐
amitph
amitph.com › home › java › how to download a file from url in java
How to Download a File from URL in Java - amitph
November 22, 2024 - The Apache Commons IO library provides a number of useful abstractions for general-purpose File IO. In order to read a file from a URL and save it to disk, we can use copyURLToFile method provided by FileUtils class.
🌐
Stack Abuse
stackabuse.com › how-to-download-a-file-from-a-url-in-java
How to Download a File from a URL in Java
August 21, 2018 - As you can see we open up a connection using the URL object and then read it via the BufferedInputStreamReader object. The contents are read as bytes and copied to a file in the local directory using the FileOutputStream. To lower the number of lines of code we can use the Files class available ...
🌐
Alvin Alexander
alvinalexander.com › blog › post › java › java-how-read-from-url-string-text
Java URL and URLConnection example - how to read content from a URL | alvinalexander.com
Use the URL object to create a Java URLConnection object. Read from the URLConnection using the InputStreamReader and BufferedReader.
🌐
Coderanch
coderanch.com › t › 782500 › java › URL-URI-local-files
URL, URI and local files (Java in General forum at Coderanch)
June 27, 2024 - Tim Holloway wrote:"file:///G|/path/to/file" This is the one I'm familiar with.. JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility ... Stephan van Hulst wrote: Do you mean: Yes, Thank you, Stephan and Tim. When I started, I only knew URLs starting with 'https://', so I thought of using 'file://', as we say in Dutch 'not hindered by any relevant knowledge'.
Top answer
1 of 12
153

Now that some time has passed since the original answer was accepted, there's a better approach:

String out = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A").next();

If you want a slightly fuller implementation, which is not a single line, do this:

public static String readStringFromURL(String requestURL) throws IOException
{
    try (Scanner scanner = new Scanner(new URL(requestURL).openStream(),
            StandardCharsets.UTF_8.toString()))
    {
        scanner.useDelimiter("\\A");
        return scanner.hasNext() ? scanner.next() : "";
    }
}
2 of 12
99

This answer refers to an older version of Java. You may want to look at ccleve's answer.


Here is the traditional way to do this:

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

public class URLConnectionReader {
    public static String getText(String url) throws Exception {
        URL website = new URL(url);
        URLConnection connection = website.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                    connection.getInputStream()));
        
        StringBuilder response = new StringBuilder();
        String inputLine;

        while ((inputLine = in.readLine()) != null)
            response.append(inputLine);

        in.close();

        return response.toString();
    }

    public static void main(String[] args) throws Exception {
        String content = URLConnectionReader.getText(args[0]);
        System.out.println(content);
    }
}

As @extraneon has suggested, ioutils allows you to do this in a very eloquent way that's still in the Java spirit:

 InputStream in = new URL( "http://jakarta.apache.org" ).openStream();

 try {
   System.out.println( IOUtils.toString( in ) );
 } finally {
   IOUtils.closeQuietly(in);
 }
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-download-file-url
Java Download File from URL | DigitalOcean
August 4, 2022 - downloadUsingStream: In this method of java download file from URL, we are using URL openStream method to create the input stream. Then we are using a file output stream to read data from the input stream and write to the file. downloadUsingNIO: In this download file from URL method, we are ...
🌐
Gnostice
gnostice.com › nl_article.asp
How To Read A PDF File From A URL In Java
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ConnectException; import java.net.URL; import java.net.URLConnection; import com.gnostice.pdfone.PdfDocument; public class Read_PDF_From_URL { public static void main(String[] args) throws IOException { URL url1 = new URL("http://www.gnostice.com/downloads/Gnostice_PathQuest.pdf"); byte[] ba1 = new byte[1024]; int baLength; FileOutputStream fos1 = new FileOutputStream("download.pdf"); try { // Contacting the URL System.out.print("Connecting to " + url1.toString() + " ...
🌐
Florida State University
cs.fsu.edu › ~jtbauer › cis3931 › tutorial › networking › urls › readingURL.html
Reading Directly from a URL
import java.net.*; import java.io.*; public class URLReader { public static void main(String[] args) throws Exception { 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(); } } When you run the program, you should see, scrolling by in your command window, the HTML commands and textual content from the HTML file located at http://www.yahoo.com/. Alternatively, the program might hang or you might see an exception stack trace.
🌐
GeeksforGeeks
geeksforgeeks.org › java › url-getfile-method-in-java-with-examples
URL getFile() method in Java with Examples - GeeksforGeeks
December 31, 2018 - url.getFile() Parameter: This function does not require any parameter Return Type: The function returns String Type Below programs illustrates the use of getFile() function: Example 1: Given a URL we will get the file using the getFile() function.
🌐
Javatpoint
javatpoint.com › java-url-getfile-method
Java URL getFile() Method with Examples - Javatpoint
Java URL getFile() Method with Examples on java, url, class getDefaultPort(), equals(), getAuthority(), getContent(), getFile(), getHost(), getPath(), getPort(), getProtocol(), getRef(), getUserInfo(), hashCode(), openConnection(), sameFile, toExternalfile(), toString(), toURI() etc.