下载文件并将其读入ArrayList?

时间:2010-06-19 16:50:48

标签: java download

public void getWebContent() throws Exception {
    Scanner in = new Scanner(System.in);
    System.out.println("Input URL:");
    fileURL = in.nextLine();
    if (!fileURL.startsWith("http://")) {
        System.out.println("URL not valid! Please make sure 'http://' prefixes");
        System.out.println("the web address!");
    } else {
        Scanner url = new Scanner(new URL(fileURL).openStream());
        System.out.println("Here are the contents:");
        while (url.hasNextLine()) {
            System.out.println(url.nextLine());
        }
        System.out.println("Would you like this to be your new Diary?");
        command = in.nextLine();
        if (command.equalsIgnoreCase("yes")) {
            diary.clear();
            while (url.hasNextLine()) {
                diary.add(url.nextLine());
            }
            System.out.println("New Diary created.");
        } else {
            System.out.println("Download cancelled. Returning to first command entry.");
        }
    }
}

据我所知,这个方法getWebContent()可以正常运行,直到它尝试将读取的Web文件添加到ArrayList<String> diary中。老实说,我不知道什么是错的,但我知道你的智能裤子可以解决它的问题:)!

2 个答案:

答案 0 :(得分:1)

当你到达代码中的那一点时,你已经阅读了扫描仪中的所有行:

while (url.hasNextLine()) {
    System.out.println(url.nextLine());
}

Scanner has a cursor that advances when you call nextLine()

答案 1 :(得分:1)

    while (url.hasNextLine()) {
        System.out.println(url.nextLine());
    }

这将清空流。由于已读取所有数据,因此List不会添加任何内容。

另外,Scanner对编码错误非常敏感 - 请参阅ioException()方法 - 为了使代码可移植,您应该对正在阅读的字符数据使用适当的编码