Get current path of executed file

后端 未结 3 1438
孤独总比滥情好
孤独总比滥情好 2021-01-28 01:47

I try to write and read to the file in my java project file called Books.txt. The problem is that I can access the file only if partialPath has full path to the file.

He

3条回答
  •  时光说笑
    2021-01-28 02:38

    Here is a code snippet of the Drombler Commons - Client Startup code I wrote, to determine the location of the executable jar. Replace DromblerClientStarter with your main class. This should work at least when you're running your application as an executable JAR file.

    /**
     * The jar URI prefix "jar:"
     */
    private static final String FULL_JAR_URI_PREFIX = "jar:";
    /**
     * Length of the jar URI prefix "jar:"
     */
    private static final int FULL_JAR_URI_PREFIX_LENGTH = 4;
    
    private Path determineMainJarPath() throws URISyntaxException {
        Class type = DromblerClientStarter.class;
        String jarResourceURIString = type.getResource("/" + type.getName().replace(".", "/") + ".class").toURI().
                toString();
        int endOfJarPathIndex = jarResourceURIString.indexOf("!/");
        String mainJarURIString = endOfJarPathIndex >= 0 ? jarResourceURIString.substring(0, endOfJarPathIndex)
                : jarResourceURIString;
        if (mainJarURIString.startsWith(FULL_JAR_URI_PREFIX)) {
            mainJarURIString = mainJarURIString.substring(FULL_JAR_URI_PREFIX_LENGTH);
        }
        Path mainJarPath = Paths.get(URI.create(mainJarURIString));
        return mainJarPath;
    }
    

    Depending on where you bundle Books.txt in your application distribution package, you can use this mainJarPath to determine the path of Books.txt.

提交回复
热议问题