小编典典

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

java

我正在尝试从在线文本文件中读取一些单词。

我试图做这样的事情

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

作为输出,我只想知道所有的话。

我知道他们是在那天教给我的,但是我现在不记得确切怎么做,非常感谢您的帮助。


阅读 245

收藏
2020-09-08

共1个答案

小编典典

使用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.
}
2020-09-08