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”?
Consegui resolver.
Criei uma classe que me dá o path do projeto. Só funciona para web, pois eu preciso do HttpServletRequest
[code]package com.inwebpartners.utils;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import br.com.caelum.vraptor.ioc.Component;
/**
*/
@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;
}
}[/code]
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());
}