现在的位置: 首页 > 综合 > 正文

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

2014年10月09日 ⁄ 综合 ⁄ 共 2181字 ⁄ 字号 评论关闭

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

[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.    }  

抱歉!评论已关闭.