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


