Relative path in Java

Asked

Viewed 1,761 times

0

I need to read a txt. Only my project has to be extensible. type q does not only work on my machine. I think the txt file would have to stay in the project folder, and put a relative path. but I don’t know how to do that. help me.

Currently parts of the code are like this:

ManipuladorArquivo manipuladorArquivo = new ManipuladorArquivo("C:\\Users\\Vinicius\\Downloads\\politicos.txt");

public class ManipuladorArquivo {

   private String caminhoArquivo;

   public ManipuladorArquivo(String caminhoArquivo) {
       this.caminhoArquivo = caminhoArquivo;
   }
}
  • String pathDoFile = new File(""). getAbsolutePath(); pathDoArchive.Concat("politicos.txt"); This results?

2 answers

1

The paths in Java are relative to where your . jar is located, you who are passing an absolute path in your variable.

Relative paths will also be different in Ides as you program.

For example, using Intellij, the IDE will create a hierarchy similar to this.

projeto/
  src/
    Main.java
  photos/ 
    icone.png

If I want to access icone.png using relative paths:

String path = "photos/icone.png";

If I want to access icone.png using absolute paths:

String path = "C:/Users/Alguem/projeto/photos/icone.png";
  • I use Netbeans, but I haven’t found where this . jar is to pass the way from it.

0


If you want the file to be in the project, just enter your project folder and paste the file in. then as stated in the previous answer, you pass the path relative to the location of the file that is calling it.

if your file is at the root of the project and your file too, just call it direct;

String caminho = "arquivo.txt";

relative path:

Files in the same location:

 String caminho = "arquivo.txt";

File in a previous folder, turn and call the file:

String caminho = "../arquivo.txt";

File in a folder in front, calls the folder and the file:

String caminho = "pasta/arquivo.txt";

remembering that it is always from the place where your script will call the.txt file;

now if you want to call from another place of the computer, you have several options, but one of them is to use the variables of windows.

example: "C:\\Users\\%USERNAME%\\Downloads\\politicos.txt";

Browser other questions tagged

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