如何使用Java直接从互联网读取文本文件?

46
我试图从在线文本文件中读取一些单词。
我尝试了这样的方法。
File file = new File("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner scan = new Scanner(file);

但它没有起作用,我得到了

http://www.puzzlers.org/pub/wordlists/pocket.txt 
作为输出,我只想获取所有单词。 我知道他们曾经在那天教过我这个,但现在我不太记得如何做了,非常感谢任何帮助。

可能是重复的问题:如何在Java中以编程方式下载网页 - Robin Green
9个回答

69

使用 URL 替代 File 来访问不在您本地计算机上的任何内容。

URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner s = new Scanner(url.openStream());
实际上,URL甚至更加普遍有用,也可以用于本地访问(使用file: URL),jar文件以及几乎所有可以以某种方式检索到的内容。
上述方法会使用您平台的默认编码来解释文件。如果您想要使用服务器指定的编码,则必须使用URLConnection并解析其内容类型,如此问题的答案中所示。
关于您的错误,请确保您的文件在没有任何错误的情况下编译 - 您需要处理异常。点击IDE给出的红色消息,它应该会向您显示一个建议如何修复它。不要启动一个不能编译的程序(即使IDE允许这样做)。
这里提供一些样例异常处理:
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.
}

1
我遇到了错误,异常线程 "main" java.lang.Error:未解决的编译问题:未处理的异常类型 MalformedURLException,未处理的异常类型 IOException。 - randomizertech
将其放在try/catch块中,并捕获这两个异常。 - Sean
1
对不起,我有点迷失了,这不应该很容易只需要两三行代码就能完成吗? - randomizertech
我尝试了这种方法,但是出现了以下错误:java.io.IOException: Server returned HTTP response code: 403 for URL:... 有什么想法吗? - theexplorer
1
@theexplorer 请参考https://zh.wikipedia.org/wiki/HTTP_403 ,例如。看起来您的服务器配置不允许下载此文件。 - Paŭlo Ebermann
1
我明白了,谢谢。请问请求主机关闭这个安全开关是明智的吗? - theexplorer

13

可以尝试这样做

 URL u = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
 InputStream in = u.openStream();

然后将其用作任何普通的输入流


9

对我真正起作用的是:(来源:Oracle文档“阅读URL”)

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

 public class UrlTextfile {
public static void main(String[] args) throws Exception {

    URL oracle = new URL("http://yoursite.com/yourfile.txt");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(oracle.openStream()));

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

6
使用 Apache Commons IO 库:
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public static String readURLToString(String url) throws IOException
{
    try (InputStream inputStream = new URL(url).openStream())
    {
        return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    }
}

3

使用以下代码将互联网资源读入到String中:

public static String readToString(String targetURL) throws IOException
{
    URL url = new URL(targetURL);
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(url.openStream()));

    StringBuilder stringBuilder = new StringBuilder();

    String inputLine;
    while ((inputLine = bufferedReader.readLine()) != null)
    {
        stringBuilder.append(inputLine);
        stringBuilder.append(System.lineSeparator());
    }

    bufferedReader.close();
    return stringBuilder.toString().trim();
}

这是基于这里的内容。


2

如果您要使用旧版输入流,请使用以下代码:

  InputStream in = new URL("http://google.com/").openConnection().getInputStream();

2
我遇到了一个错误:类型Test中未定义方法URL(URL)。 - randomizertech
用 openStream() 替换 openConnection().getInputStream() ;) - hhafez
你需要加上 "new" - 我猜你在 "URL(..." 前面省略了 "new"。 - Bohemian

2
我为图像采用以下方法进行了操作,您应该能够使用类似的步骤来处理文本。
// folder & name of image on PC          
File fileObj = new File("C:\\Displayable\\imgcopy.jpg"); 

Boolean testB = fileObj.createNewFile();

System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);

// image on server
URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg"); 
InputStream webIS = url.openStream();

FileOutputStream fo = new FileOutputStream(fileObj);
int c = 0;
do {
    c = webIS.read();
    System.out.println("==============> " + c);
    if (c !=-1) {
        fo.write((byte) c);
    }
} while(c != -1);

webIS.close();
fo.close();

0

0

或者,您可以使用Guava的资源对象:

URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
lines.forEach(System.out::println);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接