gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:44:52 28 4
gpt4 key购买 nike

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

我试着做这样的事情

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 

作为输出,我只想得到所有的单词。

我知道他们以前教过我这个,但我现在不记得具体该怎么做,非常感谢任何帮助。

最佳答案

对于不在本地计算机上的任何访问,请使用 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 并解析它的内容类型,如 this question 的答案中所示。 .


关于您的错误,请确保您的文件编译时没有任何错误 - 您需要处理异常。单击 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.
}

关于java - 如何使用 Java 直接从 Internet 读取文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6259339/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com