2010-06-19 20 views
1
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。我真的不知道什么是错的,但我知道你在那里可以弄明白:)。下载文件并将其读入ArrayList中?

回答

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

这将清空流。因为所有数据都已被读取,所以List将不会被添加。

顺便说一句,Scanner是编码错误很敏感 - 看到ioException()方法 - 使代码的可移植性,你应该使用适当的编码您正在阅读的字符数据。

相关问题