Criando um arquivo para download
Autor: Cristiano Pires | Publicado: 2011-11-14T16:50:00-02:00


Tutorial de como criar um arquivo de texto e fazer o download no navegador com JSF.

Vou criar um arquivo do tipo csv. Após ser criado o arquivo será feito o download do mesmo.

Aqui preparo o arquivo o caminho (path), informo o tipo de arquivo (mais opções de tipo de arquivo aqui), crio o arquivo e mando pra download.
Observe que o nome do arquivo é arquivo_ + a data de hoje.
O tipo de arquivo é texto (text/plain).

O método exportaCSV()


public&nbsp;void&nbsp;exportaCSV()&nbsp;throws&nbsp;DaoException&nbsp;{

&nbsp;&nbsp;FacesContext&nbsp;ctx&nbsp;=&nbsp;FacesContext.getCurrentInstance();

&nbsp; String&nbsp;file&nbsp;=&nbsp;Utils.pathArquivo("arquivo_"&nbsp;+&nbsp;new&nbsp;SimpleDateFormat("dd-MM-yyyy").format(new&nbsp;Date())&nbsp;+&nbsp;".csv");

&nbsp;&nbsp;String&nbsp;mimeType&nbsp;=&nbsp;"text/plain";

&nbsp;&nbsp;createFile();

&nbsp;&nbsp;Utils.downloadFile(mimeType,&nbsp;ctx,&nbsp;file);

}




O método pathArquivo da classe Utils. Pega o path real da aplicação




public&nbsp;static&nbsp;String&nbsp;pathArquivo(String&nbsp;fileName)&nbsp;{

&nbsp;&nbsp;FacesContext&nbsp;ctx&nbsp;=&nbsp;FacesContext.getCurrentInstance();

&nbsp;&nbsp;HttpServletRequest&nbsp;request&nbsp;=&nbsp;(HttpServletRequest)&nbsp;ctx

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.getExternalContext().getRequest();
&nbsp;&nbsp;//Observe que o arquivo index.html está na raiz da aplicação. Pego o diretório a partir dele

&nbsp;&nbsp;String&nbsp;caminho&nbsp;=&nbsp;request.getRealPath("/index.html");



&nbsp;&nbsp;int&nbsp;index&nbsp;=&nbsp;caminho.lastIndexOf("/");



&nbsp;&nbsp;caminho&nbsp;=&nbsp;caminho.substring(0,&nbsp;++index);

&nbsp;&nbsp;return&nbsp;caminho&nbsp;+&nbsp;fileName;

}&nbsp;



Criando o arquivo...


private&nbsp;void&nbsp;createFile()&nbsp;throws&nbsp;DaoException&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;List&lt;Terminal&gt;&nbsp;lista&nbsp;=&nbsp;new&nbsp;TerminalService().getListaDeTodosTerminais(); //preencho a lista com uma consulta do banco de dados

&nbsp;&nbsp;

&nbsp;&nbsp;&nbsp;&nbsp;//verifico&nbsp;se&nbsp;o&nbsp;arquivo&nbsp;existe.&nbsp;Se&nbsp;sim&nbsp;apago&nbsp;e&nbsp;crio&nbsp;um&nbsp;novo.

&nbsp;&nbsp;&nbsp;&nbsp;try&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;boolean&nbsp;exists&nbsp;=&nbsp;(new&nbsp;File(file)).exists();

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(exists)&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(new&nbsp;File(file)).delete();

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;File&nbsp;f&nbsp;=&nbsp;new&nbsp;File(file);



&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;boolean&nbsp;success&nbsp;=&nbsp;f.createNewFile();

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(success)&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;copyToFile(lista);

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;else&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;throw&nbsp;new&nbsp;DaoException("Erro&nbsp;ao&nbsp;tentar&nbsp;criar&nbsp;o&nbsp;arquivo!");

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;catch&nbsp;(IOException&nbsp;e)&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;}

}



Preenchendo o arquivo&nbsp;&nbsp;


private&nbsp;void&nbsp;copyToFile(List&nbsp;lista)&nbsp;{

&nbsp;&nbsp;try&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BufferedWriter&nbsp;out&nbsp;=&nbsp;new&nbsp;BufferedWriter(new&nbsp;FileWriter(file,&nbsp;true));

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

&nbsp;&nbsp;&nbsp;&nbsp;//colunas (1.ª linha)

&nbsp;&nbsp;&nbsp;&nbsp;out.write("\"prefixo\";\"ddd\";\"numero\"\n");

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;(int&nbsp;i=0;&nbsp;i&lt;lista.size();&nbsp;i++)&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Object[]&nbsp;o&nbsp;=&nbsp;(Object[])&nbsp;lista.get(i);

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//linhas&nbsp;

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.write("\""+&nbsp;o[0]&nbsp;+"\";\""+o[1]+"\";\""+o[2]+"\"\n");

&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.close();

&nbsp;&nbsp;}&nbsp;catch&nbsp;(IOException&nbsp;e)&nbsp;{

&nbsp;&nbsp;}
}

O método downloadFile, que é quem vai fazer o download do arquivo


public&nbsp;static&nbsp;void&nbsp;downloadFile(String&nbsp;mimeType,&nbsp;FacesContext&nbsp;ctx,&nbsp;String&nbsp;file)&nbsp;{

&nbsp;&nbsp;ExternalContext&nbsp;ectx&nbsp;=&nbsp;ctx.getExternalContext();

&nbsp;&nbsp;File&nbsp;f&nbsp;=&nbsp;new&nbsp;File(file);

&nbsp;&nbsp;HttpServletResponse&nbsp;resp&nbsp;=&nbsp;(HttpServletResponse)&nbsp;ectx.getResponse();

&nbsp;&nbsp;resp.setHeader("Content-Disposition",&nbsp;"attachment;filename="&nbsp;+&nbsp;file&nbsp;+&nbsp;"");&nbsp;

&nbsp;&nbsp;resp.setContentLength((int)&nbsp;f.length());

&nbsp;&nbsp;resp.setContentType(mimeType);



&nbsp;&nbsp;try&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;FileInputStream&nbsp;in&nbsp;=&nbsp;new&nbsp;FileInputStream(f);

&nbsp;&nbsp;&nbsp;&nbsp;OutputStream&nbsp;out&nbsp;=&nbsp;resp.getOutputStream();

&nbsp;&nbsp;&nbsp;&nbsp;byte[]&nbsp;buf&nbsp;=&nbsp;new&nbsp;byte[(int)&nbsp;f.length()];

&nbsp;&nbsp;&nbsp;&nbsp;int&nbsp;count;

&nbsp;&nbsp;&nbsp;&nbsp;while&nbsp;((count&nbsp;=&nbsp;in.read(buf))&nbsp;&gt;=&nbsp;0)&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.write(buf,&nbsp;0,&nbsp;count);

&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;&nbsp;&nbsp;in.close();

&nbsp;&nbsp;&nbsp;&nbsp;out.flush();

&nbsp;&nbsp;&nbsp;&nbsp;out.close();

&nbsp;&nbsp;&nbsp;&nbsp;ctx.responseComplete();

&nbsp;&nbsp;}&nbsp;catch&nbsp;(IOException&nbsp;ioe)&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;System.err.println(ioe.getMessage());

&nbsp;&nbsp;}
}

Simples assim!