文件流

来源:互联网 发布:壳域名有什么用 编辑:程序博客网 时间:2024/05/17 04:39


文件流常见问题:

一、java.io.FileNotFoundException: D:\awgytools\tomcat-7.0.62\webapps\platform (拒绝访问。)

解决办法:具体到文件名字。


示例一

通过二进制生成图片:

String getProjectPath=request.getSession().getServletContext().getRealPath("/");
System.out.println(getProjectPath);
        FileOutputStream fout = new FileOutputStream(getProjectPath+"/"+filename);  //具体到文件名
        fout.write(photoBytes);

        fout.close();  


示例二

/**
* 通过数据库Blob字段生成图片
* @param request
* @param photo
* @param iconUrl
* @throws IOException 
*/
public void initIcon(HttpServletRequest request,Object photo,String iconUrl) throws IOException{
String outfile=request.getSession().getServletContext().getRealPath("/")+"\\"+iconUrl;//D:\awgytools\tomcat-7.0.62\webapps\platform\\img\f9a52792-84b0-4e71-94f6-42ee03ab642d6.png
FileOutputStream fos = null;  
try{
byte[] Buffer = new byte[4096];  
Blob blob = (Blob) photo;
InputStream is =blob.getBinaryStream();;//注意转换
int size = 0; 
file = new File(outfile);  
if(!file.exists()){  
file.createNewFile();     //如果文件不存在,则创建  

fos = new FileOutputStream(file);  
while((size = is.read(Buffer)) != -1){  
fos.write(Buffer,0,size);  
}  
fos.write(Buffer,0,1);  
}catch(Exception e){
System.out.println("[OutPutFile error : ]" + e.getMessage());
}finally{
//关闭用到的资源  
fos.close();  
}
}

0 0