[Java]远程下载文件并读取实例方法


简单的文件下载后读取显示,该方法可返回内容的结果集。一般适用于文本文档的下载,以供学习交流。


[java]  view plain copy
  1. /** 
  2.     * 远程下载文件并读取返回p 
  3.     * @param filePath 文件网络地址 如http://www.baidu.com/1.txt 
  4.     * @return String 
  5.     */  
  6.    public String DownAndReadFile(String filePath){  
  7.        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());      
  8.        File savePath = new File("D://"+date);//创建新文件  
  9.        if (!savePath.exists()) {   
  10.            savePath.mkdir();   
  11.        }  
  12.        String[] urlname = filePath.split("/");  
  13.        int len = urlname.length-1;  
  14.        String uname = urlname[len];//获取文件名  
  15.        try {  
  16.            File file = new File(savePath+"//"+uname);//创建新文件  
  17.            if(file!=null && !file.exists()){  
  18.                file.createNewFile();  
  19.            }  
  20.            OutputStream oputstream = new FileOutputStream(file);  
  21.            URL url = new URL(filePath);  
  22.            HttpURLConnection uc = (HttpURLConnection) url.openConnection();  
  23.            uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true  
  24.            uc.connect();  
  25.            InputStream iputstream = uc.getInputStream();  
  26.            System.out.println("file size is:"+uc.getContentLength());//打印文件长度  
  27.            byte[] buffer = new byte[4*1024];  
  28.            int byteRead = -1;     
  29.            while((byteRead=(iputstream.read(buffer)))!= -1){  
  30.                oputstream.write(buffer, 0, byteRead);  
  31.            }  
  32.            oputstream.flush();    
  33.            iputstream.close();  
  34.            oputstream.close();  
  35.            //读取文件  
  36.            StringBuffer strb = new StringBuffer();  
  37.            FileInputStream fs = new FileInputStream(new File(savePath+"//"+uname));  
  38.            InputStreamReader isr = new InputStreamReader(fs,"UTF-8");  
  39.            BufferedReader br = new BufferedReader(isr);  
  40.            String data = "";  
  41.            while((data = br.readLine()) != null){  
  42.                strb.append(data + "\n");  
  43.            }  
  44.            br.close();  
  45.            fs.close();  
  46.            isr.close();  
  47.            System.out.println(strb.toString());  
  48.            return strb.toString();  
  49.              
  50.     } catch (Exception e) {  
  51.         System.out.println("读取失败!");  
  52.         e.printStackTrace();  
  53.     }     
  54.        return null;  
  55.    }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值