在项目中,经常会遇到要读取文件,为了避免自己技术遗忘,还是决定写写博客。
public void doinput(String filePath ){
OutputStream os=null;
InputStream input=null;
try{
//传入的参数 filePath 就是要读取文件的路径
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("GBK");
//流能够自动识别文件的类型
//response.setContentType("application/pdf");
os = response.getOutputStream();
input = new FileInputStream(filePath);
//通过控制一次读取文件的长度 来避免一次性将文件全部读出来造成性能的损耗
byte[] byteData = new byte[1024];
int num;
while((num=input.read(byteData))!=-1){
os.write(byteData, 0, num);
}
}catch(Exception ex){
ex.printStackTrace();
}
finally{
if(input!=null)
{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}