简体   繁体   中英

How to get the path of a file in my java project when running java from batch file?

I have a Java 8 application running on Windows. I would like to locate a file in my Java project without using the absolute path. The following code works when I run my application from a command prompt: System.getProperty("user.dir") . However, when I run my java application from a batch file, this code return the path of the batch file, which is not the same as the path of the java application.

How do I get the path of file abc.txt that is located in a folder in my Java project?

System.getProperty("user.dir") got you the right directory because your application was started in the batch file. It's the way it works.

You can always load your files in your application by using a ClassLoader.

Say you have put abc.txt inside your project folder. Actually, if you're using it somewhere in your code as a resource file, you should put it in src/resources folder of your project. Then in your code, do things as below:

   File file = new File(getClass().getResource("abc.txt").getFile());

That will give you access to the file no matter where your application starts.

Taking a look at this post on using ClassLoader will help you get a better sense on how to load resources in Java.

UPDATE

这是我在Eclipse中的项目 , abc.txt is under src folder, which is in the class path.

The MyClass.java only contains below code:

    public class MyClass {
        public static void main(String[] args) {
            System.out.println("s: " + MyClass.class.getClassLoader().getResource("abc.txt").getFile());
        }
    }

I had the same problem and the only work around I found after searching A LOT was locating the starter Batch file in the same path as the java application, then generate a shortcut of the batch and this is what I could place anywhere in other folders....

After that, the java was running fine...

Assuming that you basically want to have relative paths in your code, You can use the below function to get the source directory and then get any file using the relative location of the file within your source code path.

public static String getMySourcePath() {
        URL location = <Your class>.class.getProtectionDomain().getCodeSource()
                .getLocation();
        String srcPath = location.toString().replace("file:/", "")
                .replace("bin", "src");
        return srcPath;
    }

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