1

I have a program that sends a file from server to client in java. The program consists of two main folders "Server" and "Client" these folders are stored in a main "Project1" folder. The "Server" folder contains a Server.class file and "ServerFiles" folder which contains a .txt file. The "Client" folder contains a Client.class file and a "ClinetFiles" folder which contains nothing(this is where the server send the .txt file to). At the moment I am providing the whole path for both File folders.

My question is what should my path be so the the program works in any directory.

I tried ./Project1/Client for the client and ./Project1/Server/file.txt for the server

but these are not recognized

System32
  • 63
  • 5

3 Answers3

3

Relative paths are relative to the program's current working directory, which by default is the directory in which the command to launch java was executed. The working directory can also be defined using the -Duser.dir parameter passed to java.

As an alternative to relying on the working directory, you can set a system property or environment variable containing the top-level data directory path. Then read this variable in at runtime and prepend that to your sub-path when you're accessing files within the data directory.

jspcal
  • 50,847
  • 7
  • 72
  • 76
  • If you `cd` to or set `user.dir` to `C:/Users/Documents/Projects/Project1/testing/filepost` then the relative path to use in your code would be `client/clientFiles/test.txt`. – jspcal Apr 03 '19 at 23:11
0

You should just use relative paths. Not sure how many folders back you should go but the idea is File file = new File("..\\..\\..\\Client\\ClientFiles\\file.txt");

NOTE: taken from How to define a relative path in java (Windows)

tsvedas
  • 1,049
  • 7
  • 18
0

One potential solution is to use the getResource method of the Class object to get a reference point for your path. Something like:

import java.io.File;
import java.net.URL;

public class MyClass {

    public static void main(String[] args) throws Exception {
        File applicationRoot = getApplicationRootFile();
        System.out.println(applicationRoot.getCanonicalPath());
    }

    private static File getApplicationRootFile() {
        URL url = MyClass.class.getResource(".");
        String path = url.getPath();
        File file = new File(path + "../../");
        return file;
    }

}
John
  • 3,458
  • 4
  • 33
  • 54