[RESOLVIDO] Como escrever aquivo usando o IOUtils do Commons IO?

1 resposta
M

Olá, gostaria de saber se tem como escrever um arquivo a partir do diretório do projeto.

Estou fazendo o seguinte:

File imageFile = new File("" + lastWebSiteBannerRegistered.getNumericIdentifier() + ".jpg"); try { IOUtils.copy(webSiteBannerAddRequestInput.getImage().getFile(), new FileOutputStream(imageFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

Ele salva o arquivo, mas na pasta do usuário do sistema.

Como ficaria para salvar, por exemplo: “pastaDoProjeto/WebContent/image/banner/nomeDoArquivo.jpg”?

1 Resposta

M

Consegui resolver.

Criei uma classe que me dá o path do projeto. Só funciona para web, pois eu preciso do HttpServletRequest
package com.inwebpartners.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import br.com.caelum.vraptor.ioc.Component;

/**
 * @author maiconfz
 * 
 */
@Component
public class ProjectPathProvider {
	private static Logger LOGGER = Logger.getLogger(ProjectPathProvider.class);
	private final HttpServletRequest request;

	/**
	 * @param request
	 */
	public ProjectPathProvider(HttpServletRequest request) {
		this.request = request;
	}

	public String getProjectPath() {
		LOGGER.debug("Method getProjectPath() has started.");
		String projectPath = this.request.getServletContext().getRealPath("/");
		LOGGER.debug("Project path discovered is " + projectPath);
		LOGGER.debug("Method getProjectPath() has finished, returning"
				+ projectPath + ".");
		return projectPath;
	}
}
Depois usei um objeto dessa classe para a criação do meu arquivo:
File imageFile = new File(this.projectPathProvider.getProjectPath()
		+ "WEB-INF/jsp/image/banner/"
		+ lastWebSiteBannerRegistered.getNumericIdentifier()
		+ ".jpg");
try {
	IOUtils.copyLarge(webSiteBannerAddRequestInput.getImage()
			.getFile(), new FileOutputStream(imageFile));
} catch (FileNotFoundException e) {
	e.printStackTrace();
	throw new IllegalStateException(e.getCause());
} catch (IOException e) {
	e.printStackTrace();
	throw new IllegalStateException(e.getCause());
}
Criado 17 de junho de 2012
Ultima resposta 18 de jun. de 2012
Respostas 1
Participantes 1