简体   繁体   中英

JAVA and GIT How to manage external resources. DONE RIGHT TECHNIQUE

What is the right technique to manage external file in a Java project? Or more generally in any project.

I'm currently using the IDE IntelliJ, but I want this to be a more general solution instead of a IDE dependent solution.

I have the following folder structure:

├── headers
│   └── header1
├── htmlfiles
│   └── reply1.html
├── out
│   └── production
│       └── WebApp-e01
│           └── ch
│               └── miao
│                   └── webapp
│                       └── server
│                           ├── Content.class
│                           ├── Request.class
│                           └── Server.class
├── README.md
├── src
│   └── ch
│       └── miao
│           └── webapp
│               └── server
│                   ├── Content.java
│                   ├── Request.java
│                   └── Server.java <-- MAIN HERE
└── WebApp-e01.iml

I cloned the project from git that was on my other laptop so the absolute file path is no more valid, because the user name could be different or the project name or the location or many other things.

So this means a line of code like this inside any class in no longer valid.

BufferedReader reader = new BufferedReader(new FileReader("/home/kevin/IdeaProjects/ApplicazioniWeb/htmlfiles/reply1.html"))

Then I tried with relative paths:

BufferedReader reader = new BufferedReader(new FileReader("./htmlfiles/reply1.html"))

This works "well" if I run it from Intellij (because of magic) but if I want to run it the good old way from the console:

java ch.miao.webapp.server.Server

in order to make it work I have to change AGAIN, the paths inside my classes, and depending on which IDE I'm using this could change because inetellij puts all the stuff inside out/production/... but other IDEs have different locations, and this is a nightmare if you work in team!

So I want to know if there is a general solution where I can just run my program form the IDE or form the command line and form any other workstation after I cloned my project from git without have to change my file paths.

You can use Java system property called "user.dir". Its name might be a bit misleading, because it points to the directory, where JVM was started.

String workingDirectory = System.getProperty("user.dir");
File file = new File(workingDirectory + File.separator + "htmlfiles" + File.separator + "reply1");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM