JAVA 文件下载问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA 文件下载问题相关的知识,希望对你有一定的参考价值。
代码如下
@RequestMapping(params = "method=uploadfile")
public void download(@ModelAttribute("TaskAttachmentBO") TaskAttachmentBO pojo,@RequestParam(required=false) MultipartFile[] files,ModelMap modle, HttpServletRequest request,HttpServletResponse response) throws Exception
response.setContentType( "text/html" );
response.setCharacterEncoding( "UTF-8" );
JSONObject res = new JSONObject();
TaskAttachmentBO taskAttachmentBO = taskAttachmentService.queryAtta(pojo);
//String filePath = SystemSettings.path+taskAttachmentBO.getDisk_file_name();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
//获取项目根目录
String ctxPath = request.getSession().getServletContext()
.getRealPath("");
//获取下载文件露肩
String downLoadPath = ctxPath+"??"+ taskAttachmentBO.getDisk_file_name();
//获取文件的长度
long fileLength = new File(downLoadPath).length();
//设置文件输出类型
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(taskAttachmentBO.getDisk_file_name().getBytes("utf-8"), "ISO8859-1"));
//设置输出长度
response.setHeader("Content-Length", String.valueOf(fileLength));
//获取输入流
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
//输出流
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
bos.write(buff, 0, bytesRead);
//关闭流
bis.close();
bos.close();
文件保存在服务器的D:\upload文件夹下,我如何获取这个地址?SystemSettings.path获取的是配置的文件保存地址,如D:\upload,那么我downLoadPath地址如何写
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class HttpDownload
private String file_url;
private String file_path;
private String file_name;
private String logo_url;
private String logo_path;
private String logo_name;
public void setLogo_name(String logoUrl)
this.logo_name = logoUrl.substring(logoUrl.lastIndexOf("/"));
public void setLogo_path(String logoUrl)
String Path = "d:\\logo";
String partPath = logo_name.substring(1,logo_name.lastIndexOf("."));
this.logo_path = Path ;
List<String> list = new ArrayList<String>();
int beginIndex = 1;
int endIndex = 4;
while(beginIndex<partPath.length()-1)
if(endIndex>partPath.length()-1) endIndex = partPath.length();
String name = partPath.substring(beginIndex, endIndex);
if(name.length()<3)
for(int i = name.length();i<3;i++)
name+=0;
list.add(name);
beginIndex += 3;
endIndex += 3;
for(String s:list)
logo_path += "\\"+s;
System.out.println(logo_path);
public void setFile_name(String file_name)
this.file_name = file_name.substring(file_name.lastIndexOf("/"));
public boolean downLoadFile(String sURL,String name,String path)
int nStartPos = 0;
int nRead = 0;
try
URL url = new URL(sURL);
// 打开连接
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
// 获得文件长度
long nEndPos = getFileSize(sURL);
File file = new File(path);
file.mkdirs();
RandomAccessFile oSavedFile = new RandomAccessFile(path + "\\"
+ name, "rw");
httpConnection
.setRequestProperty("User-Agent", "Internet Explorer");
String sProperty = "bytes=" + nStartPos + "-";
// 告诉服务器,这个文件从nStartPos字节开始传
httpConnection.setRequestProperty("RANGE", sProperty);
System.out.println(name+"下载开始:"+sProperty);
InputStream input = httpConnection.getInputStream();
byte[] b = new byte[1024];
// 读取网络文件,写入指定的文件中
while ((nRead = input.read(b, 0, 1024)) > 0 && nStartPos < nEndPos)
oSavedFile.write(b, 0, nRead);
nStartPos += nRead;
httpConnection.disconnect();
System.out.println(name+"文件下载结束!");
return true;
catch (Exception e)
e.printStackTrace();
return false;
public String getFile_url()
return file_url;
public void setFile_url(String file_url)
this.file_url = file_url;
public String getFile_path()
return file_path;
public void setFile_path()
this.file_path = "D:\\soft";
public String getFile_name()
return file_name;
// 获得文件长度
public static long getFileSize(String sURL)
int nFileLength = -1;
try
URL url = new URL(sURL);
HttpURLConnection httpConnection = (HttpURLConnection) url
.openConnection();
httpConnection
.setRequestProperty("User-Agent", "Internet Explorer");
int responseCode = httpConnection.getResponseCode();
if (responseCode >= 400)
System.err.println("Error Code : " + responseCode);
return -2; // -2 represent access is error
String sHeader;
for (int i = 1;; i++)
sHeader = httpConnection.getHeaderFieldKey(i);
if (sHeader != null)
if (sHeader.equals("Content-Length"))
nFileLength = Integer.parseInt(httpConnection
.getHeaderField(sHeader));
break;
else
break;
catch (IOException e)
e.printStackTrace();
catch (Exception e)
e.printStackTrace();
System.out.println(nFileLength);
return nFileLength;
public String getLogo_url()
return logo_url;
public void setLogo_url(String logo_url)
this.logo_url = logo_url;
public String getLogo_name()
return logo_name;
public String getLogo_path()
return logo_path;
这是跑在我服务器上的下载程序你可以看看希望对你有帮助,有问题问就好了本回答被提问者和网友采纳
java读取json文件的问题
我现在 有个json文件,里面的内容如下:
[
text: '广州市',
cls: 'folder',
id:'4401',
children: [
text: '荔湾区',
id:'440103',
leaf: true
,
text: '越秀区',
id:'440104',
leaf: true
,
text: '海珠区',
id:'440105',
leaf: true
,
text: '天河区',
id:'440106',
leaf: true
,
text: '白云区',
id:'440111',
leaf: true
,
text: '黄埔区',
id:'440112',
leaf: true
,
text: '番禺区',
id:'440113',
leaf: true
,
text: '花都区',
id:'440114',
leaf: true
,
text: '萝岗区',
id:'440115',
leaf: true
,
text: '南沙区',
id:'440116',
leaf: true
,
text: '增城市',
id:'440183',
leaf: true
,
text: '从化市',
id:'440184',
leaf: true
]
,
text: '深圳市',
cls: 'folder',
id:'4403',
children: [
text: '罗湖区',
id:'440303',
leaf: true
,
text: '福田区',
id:'440304',
leaf: true
,
text: '南山区',
id:'440305',
leaf: true
,
text: '宝安区',
id:'440306',
leaf: true
,
text: '龙岗区',
id:'440307',
leaf: true
]
]
怎么通过id来获取text,给出直接代码参考下吧,如果可以会追分的!
Java 读写json格式的文件方法:
一、要解决这个问题首先要知道json格式是什么?
JSON格式:
比如学生有学号,姓名,性别等。
用json表示则为:
这代表一个学生的信息。
如果多个,如下:
"studno":"11111","studname":"xxxx","studsex":"男",
"studno":"33333","studname":"ssss","studsex":"男"]
这就是json格式。
二、那如何操作json格式的文件呢?
解答:就是直接读写文件,再把读出来的文件内容格式化成json就可以了。
三、具体操作:
1、有一个实体类,如下:
public class ElectSetpublic String xueqi;
public String xuenian;
public String startTime;
public String endTime;
public int menshu;
public String isReadDB;
//"xueqi":,"xuenian":,"startTime":,"endTime":,"renshu":,"isReadDB":
public String getXueqi()
return xueqi;
public void setXueqi(String xueqi)
this.xueqi = xueqi;
public String getXuenian()
return xuenian;
public void setXuenian(String xuenian)
this.xuenian = xuenian;
public String getStartTime()
return startTime;
public void setStartTime(String startTime)
this.startTime = startTime;
public String getEndTime()
return endTime;
public void setEndTime(String endTime)
this.endTime = endTime;
public int getMenshu()
return menshu;
public void setMenshu(int menshu)
this.menshu = menshu;
public String getIsReadDB()
return isReadDB;
public void setIsReadDB(String isReadDB)
this.isReadDB = isReadDB;
2.有一个json格式的文件,存的就是他的信息,如下:
Sets.json:"xuenian":"2007-2008","xueqi":"1","startTime":"2009-07-19 08:30","endTime":"2009-07-22 18:00","menshu":"10","isReadDB":"Y"
3.具体操作:
/** 取出文件内容,填充对象
*/
public ElectSet findElectSet(String path)
ElectSet electset=new ElectSet();
String sets=ReadFile(path);//获得json文件的内容
JSONObject jo=JSONObject.fromObject(sets);//格式化成json对象
//System.out.println("------------" jo);
//String name = jo.getString("xuenian");
//System.out.println(name);
electset.setXueqi(jo.getString("xueqi"));
electset.setXuenian(jo.getString("xuenian"));
electset.setStartTime(jo.getString("startTime"));
electset.setEndTime(jo.getString("endTime"));
electset.setMenshu(jo.getInt("menshu"));
electset.setIsReadDB(jo.getString("isReadDB"));
return electset;
//设置属性,并保存
public boolean setElect(String path,String sets)
try
writeFile(path,sets);
return true;
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
return false;
//读文件,返回字符串
public String ReadFile(String path)
File file = new File(path);
BufferedReader reader = null;
String laststr = "";
try
//System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
//一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null)
//显示行号
System.out.println("line " line ": " tempString);
laststr = laststr tempString;
line ;
reader.close();
catch (IOException e)
e.printStackTrace();
finally
if (reader != null)
try
reader.close();
catch (IOException e1)
return laststr;
//把json格式的字符串写到文件
public void writeFile(String filePath, String sets) throws IOException
FileWriter fw = new FileWriter(filePath);
PrintWriter out = new PrintWriter(fw);
out.write(sets);
out.println();
fw.close();
out.close();
4.调用,使用(在网站的controller里调用的):
//取出json对象public void GetElectSettings(HttpServletRequest request,
HttpServletResponse response) throws Exception
ElectSet electset=new ElectSet();
String absPath = request.getRealPath("\\");
String filePath = absPath "public\\sets\\electSets.json";
electset=businessService.findElectSets(filePath);//这里是调用,大家自己改改,我调用的业务层 的。
JSONArray jsonItems = new JSONArray();
jsonItems.add(electset);
JSONObject jo=new JSONObject();
jo.put("data", jsonItems);
System.out.println(jo);
request.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(jo);
//修改json文件
public void ChangeElectSet(HttpServletRequest request,
HttpServletResponse response) throws Exception
request.setCharacterEncoding("UTF-8");
response.setContentType("text/json;charset=utf-8");
log.info("reach ChangeElectSet");
String json = (String) request.getParameter("json").trim();
log.info("Change ElectSet");
log.info(json);
ElectSet sets = new ElectSet();
JSONObject jsonObject = JSONObject.fromObject(json);
sets = (ElectSet) JSONObject.toBean(jsonObject, ElectSet.class);
if(sets.getIsReadDB()=="false")
sets.setIsReadDB("否");
else
sets.setIsReadDB("是");
String changes=""xuenian":"";//因为json的属性要用引号,所以要用"转义一下
changes =sets.getXuenian() "","xueqi":"" sets.getXueqi() "","startTime":"" sets.getStartTime() "","endTime":"" sets.getEndTime() "","menshu":"" sets.getMenshu() "","isReadDB":"" sets.getIsReadDB() """;
System.out.println(changes);
String absPath = request.getRealPath("\\");
String filePath = absPath "public\\sets\\electSets.json"; 参考技术A <script type="text/javascript">
//JSON 取值
//len = json.length 获取JSON表达式[]中 项数。
//json[index].school_name 表示索引为index(从0开始)的“” 对象,school_name表示该对象的值
var json = school;
for (var index = 0, len = json.length; index < len; index++)
var areaid = json[index].school_id; //学校编号
var schoolname = json[index].school_name; //学校名称
var zoneid = json[index].zone_id; //区域编号
var schoolx = json[index].school_x; //学校经度
var schooly = json[index].school_y; //学校纬度
var content = "学校编号:" + areaid + "|学校名称:" + schoolname + "|区域编号:" + zoneid +
"|学校经度:" + schoolx + "|学校纬度:" + schooly + "<br/>";
document.write(content);
</script>
这个可以 按你对应的json名和项值进行改动,输出。。。本回答被提问者和网友采纳 参考技术B 使用json RPC 即可 参考技术C
这个我做过,可是我重装过系统了,不好测试。我可以给你解析json需要的jar包。其他的百度应该有的。
以上是关于JAVA 文件下载问题的主要内容,如果未能解决你的问题,请参考以下文章