Home > other >  How to write relative file path for a file in java project folder
How to write relative file path for a file in java project folder

Time:04-27

The project name is 'producer'. I have a file located in project folder C:/Users/Documents/producer/krb5.conf. If I want to write its relative path, should I write

File file = new File("krb5.conf");

or

File file = new File("producer/krb5.conf");

or

File file = new File("./krb5.conf");

?

CodePudding user response:

You can use both your 1. and 3. option.

The 2. option would refer to C:/Users/Documents/producer/producer/krb5.conf.

For the purpose of testing you could try to get the absolute path from each file and print it.

        // 1.
        File file1 = new File("krb5.conf");
        File file2 = new File("producer/krb5.conf");
        File file3 = new File("./krb5.conf");

        System.out.println(file1.getAbsolutePath());
        // Output: C:\Users\Documents\producer\krb5.conf

        System.out.println(file2.getAbsolutePath());
        // Output: C:\Users\Documents\producer\producer\krb5.conf

        System.out.println(file3.getAbsolutePath());
        // Output: C:\Users\Documents\producer\.\krb5.conf   

The 3. path may look a bit weird at first, but it also works.

C:\Users\Documents\producer\. points to the current directory, so it is essentially the same as C:\Users\Documents\producer.

  • Related