JAVA远程下载文件 总结 思路~~Myself

1.对于给定的http://ip/flows/data/xxx.txt,想要下载,本来思路直接windows.open(url)搞定

但是这样有一个问题,浏览器直接把txt打开,而无法提供下载。 

一通google后,发现JS的一些代码也解决不了。

最后想到还是用流的方式进行返回,设置返回类型为附件形式即可:

getResponse().setHeader("Content-disposition","attachment; filename="+new String(fileName.getBytes("GB2312"),"ISO-8859-1"));


2.我的解决方案:

步骤一:因为我的项目用的struts2架构,因此选择的方法先是用java远程把txt下载到服务器上:

public InputStream getInputStream() throws Exception {
String fileName = "flows_" + getSession().get(TASK_ID) + ".txt";
String fileUrl = "http://159.226.8.104/flows/data/" + fileName;
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String downPath = "D:/" + date + "/";    //本地版
//      String downPath = "/home/tempFlowTxt/";       //服务器版
downUrlTxt(fileName, fileUrl, downPath);

return new FileInputStream(downPath+fileName);
}

public void downUrlTxt(String fileName,String fileUrl,String downPath){
File savePath = new File(downPath);
      if (!savePath.exists()) {   
          savePath.mkdir();   
      }  
      String[] urlname = fileUrl.split("/");  
      int len = urlname.length-1;  
      String uname = urlname[len];//获取文件名  
      try {  
          File file = new File(savePath+"/"+uname);//创建新文件  
          if(file!=null && !file.exists()){  
              file.createNewFile();  
          }  
          OutputStream oputstream = new FileOutputStream(file);  
          URL url = new URL(fileUrl);  
          HttpURLConnection uc = (HttpURLConnection) url.openConnection();  
          uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true  
          uc.connect();  
          InputStream iputstream = uc.getInputStream();  
          System.out.println("file size is:"+uc.getContentLength());//打印文件长度  
          byte[] buffer = new byte[4*1024];  
          int byteRead = -1;     
          while((byteRead=(iputstream.read(buffer)))!= -1){  
              oputstream.write(buffer, 0, byteRead);  
          }  
          oputstream.flush();    
          iputstream.close();  
          oputstream.close();  
      } catch (Exception e) {  
          System.out.println("读取失败!");  
          e.printStackTrace();  
      }        
      System.out.println("生成文件路径:"+downPath+fileName); 
}


步骤二:把下载到本地的txt,用struts2方式进行下载(各种下载本地文件的方式都可以,例如fileupload或者读入流,然后以输出流方式返回浏览器)




以上解决了下载txt问题!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值