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("无效的路径!");
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容