How to get current directory of a web application?

Asked

Viewed 614 times

2

I need to know how I get the current directory of my application because I need to save some PDF files. I have tried a few times, but without success. Can anyone give me a light? Look how I’m doing:

public String salvarPDF() throws IOException {
    String nomeArquivo = FilenameUtils.getName(arquivoUploadPDF.getFileName());
    InputStream input = arquivoUploadPDF.getInputstream();
    String caminhoCompleto = System.getProperty("user.dir") + "\\src\\main\\webapp\\uploads\\pdfs";
    String caminho = "uploads\\pdfs";
    OutputStream output = new FileOutputStream(new File(caminhoCompleto, nomeArquivo));
    caminho += "\\" + nomeArquivo;

2 answers

3

Alternative:

URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
System.out.println(location.getFile());

The advantage of this version is that it also works with paths within packages (in a jar, war, ear, etc.).


Source: Soen - Getting the Current Working Directory in Java

2

It’s quite simple:

String caminhoApp = new File("").getAbsolutePath();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.