Java读取网络中的文件

String url = "http://img.baidu.com/hunter/alog/alog.min.js";
if(url!=null){
  try{
    URL getUrl = new URL(url);
    System.out.println("正在查找文件位置。。。");
    HttpURLConnection connection = (HttpURLConnection)
    getUrl.openConnection();
    connection.connect();
    System.out.println("正在读取文件中。。。");
    BufferReader reader = new BufferReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
    String strs = "";
    String line = "";
    while((line = reader.readLine())!=null){
      strs+=line;
      System.out.println(line);
    }
    reader.close();
    connection.disconnect();
    System.out.println("\nfile read");
    if(strs == null || strs.toString() == ""){
      System.err.println("文件无内容!");
    }
  } catch (IOException e){
    String ex = e.toString();
    if(ex.indexOf("FileNotFoundException")>0){
      System.err.println("文件不存在!");
    }else{
      System.err.println("访问目标文件失败!");
    }
  }
}else{
  System.err.println("无效的路径!");
}

你可能感兴趣的:(Java读取网络中的文件)