segunda-feira, 16 de agosto de 2010

Operações com arquivos

 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.io.OutputStream;  
 import javax.faces.context.ExternalContext;  
 import javax.faces.context.FacesContext;  
 import javax.servlet.http.HttpServletResponse;  
 public class OperacoesArquivos {  
   public static synchronized void downloadFile(String filename, String fileLocation, String mimeType,  
                          FacesContext facesContext) {  
     String path = fileLocation; // Localizacao do arquivo  
     String fullFileName = path + filename;  
     File file = new File(path); // Objeto arquivo mesmo :)  
     OperacoesArquivos.downloadFile(filename, file, facesContext, mimeType);  
   }  
   public static synchronized void downloadFile(String filename,File arquivo,FacesContext facesContext,String mimeType){  
     ExternalContext context = facesContext.getExternalContext(); // Context  
     HttpServletResponse response = (HttpServletResponse) context.getResponse();  
     try {  
       FileInputStream in = new FileInputStream(arquivo);  
       OutputStream out = response.getOutputStream();  
       byte[] buf = new byte[(int)arquivo.length()];  
       if (buf.length > 0){       
         int count;       
         while ((count = in.read(buf)) >= 0) {  
           out.write(buf, 0, count);  
         }  
       }  
       in.close();  
       out.flush();  
       out.close();  
       facesContext.responseComplete();  
     } catch (IOException ex) {  
       System.out.println("Error in downloadFile: " + ex.getMessage());  
       ex.printStackTrace();  
     }  
     response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\""); //aki eu seto o header e o nome q vai aparecer na hr do donwload  
     response.setContentLength((int) arquivo.length()); // O tamanho do arquivo  
     response.setContentType(mimeType); // e obviamente o tipo  
   }  
 }  

Nenhum comentário:

Postar um comentário