如何使用Java直接从Internet读取文本文件?

ran*_*ech 41 java file text-files java.util.scanner

我试图从在线文本文件中读取一些单词.

我尝试过做这样的事情

File file = new File("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner scan = new Scanner(file);
Run Code Online (Sandbox Code Playgroud)

但它没有用,我得到了

http://www.puzzlers.org/pub/wordlists/pocket.txt 
Run Code Online (Sandbox Code Playgroud)

作为输出,我只想得到所有的话.

我知道他们在当天教我这个,但我现在不记得到底是怎么做的,非常感谢任何帮助.

Paŭ*_*ann 60

使用URL而不是File本地计算机上没有的任何访问权限.

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

实际上,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.
}
Run Code Online (Sandbox Code Playgroud)


hha*_*fez 12

尝试这样的事情

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

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


小智 7

什么对我有用:(来源:oracle文档"阅读网址")

 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();
}
 }
Run Code Online (Sandbox Code Playgroud)


Jaw*_*wad 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);
    }
}
Run Code Online (Sandbox Code Playgroud)