gpt4 book ai didi

java - 从在线文本获取行不起作用 - 运行时出现错误

转载 作者:行者123 更新时间:2023-12-01 16:52:55 26 4
gpt4 key购买 nike

我尝试从在线文本文件输入一些地址,但运行代码时出现我不明白的错误。

错误是:

Exception in thread "main" java.util.NoSuchElementException: No line found  
at java.util.Scanner.nextLine(Unknown Source)
at Main.main(Main.java:20)

我做错了什么?

我用浏览器打开了网址文本,它打开正确(问题不在于连接或链接)
我正在使用 Windows 命令提示符

import java.net.URL;
import java.util.Scanner;

class Address
{
String street;
String city;
String state;
int zip;
}

public class WebAddresses
{
public static void main(String[] args) throws Exception
{
URL addys = new URL("http://cs.leanderisd.org/txt/fake-addresses.txt");
Scanner fin = new Scanner( addys.openStream() );

Address uno = new Address();
uno.street = fin.nextLine(); //line 20
uno.city = fin.nextLine();
uno.state = fin.next();
uno.zip = fin.nextInt();
fin.skip("\n");

Address dos = new Address();
dos.street = fin.nextLine();
dos.city = fin.nextLine();
dos.state = fin.next();
dos.zip = fin.nextInt();
fin.skip("\n");

Address tre = new Address();
tre.street = fin.nextLine();
tre.city = fin.nextLine();
tre.state = fin.next();
tre.zip = fin.nextInt();
fin.skip("\n");

fin.close();

System.out.println(uno.street + ", " + uno.city + ", " + uno.state + " " + uno.zip);
System.out.println(dos.street + ", " + dos.city + ", " + dos.state + " " + dos.zip);
System.out.println(tre.street + ", " + tre.city + ", " + tre.state + " " + tre.zip);
}
}

最佳答案

该 URL 返回 302“对象已移动”响应,将您重定向到安全协议(protocol);请注意响应的 Location header 中的 https:

curl -v http://cs.leanderisd.org/txt/fake-addresses.txt

* Trying 204.57.104.225...
* Connected to cs.leanderisd.org (204.57.104.225) port 80 (#0)
> GET /txt/fake-addresses.txt HTTP/1.1
> Host: cs.leanderisd.org
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 302 Object Moved
< Date: Thu, 07 Apr 2016 20:13:01 GMT
< Connection: Keep-Alive
< Content-Length: 0
< Location: https://cs.leanderisd.org/txt/fake-addresses.txt
<
* Excess found in a non pipelined read: excess = 1 url = /txt/fake-addresses.txt (zero-length body)
* Connection #0 to host cs.leanderisd.org left intact

您必须遵循重定向,如下所述:How to get redirected URL and content using HttpURLConnection

或者直接使用安全 URL:

https://cs.leanderisd.org/txt/fake-addresses.txt

关于java - 从在线文本获取行不起作用 - 运行时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485980/

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