0

The war I published tries to read full path. I would like it to read the file with relative path.

text.txt and war are in the same directory. the should be able to read txt in any envronment.

/at/tomcat/webapps/myapplication.war
/test.txt

I would like to

/at/tomcat/webapps/text.txt

How should I do?

JavaCode

File file = new File("./test.txt");

.classpath

    <classpath>
    <classpathentry kind="src" output="target/classes" path="src/main/java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
user14232549
  • 405
  • 4
  • 17

1 Answers1

0

That's quite difficult.

Perhaps you're looking for something else.

If the file(s) you want to read are intended to be read-only and part of your (web)app deployment, such as image files, datafiles containing static tabular data (say, a list of countries), etc - then the common thing to do is to put these files inside your jar (or war). Maven will automatically take care of this if you put these files in src/main/resources (your java files are in src/main/java, your resource files are in src/main/resources). Just like maven moves your java files into the proper position by compiling them, so does it move the resource files into the proper position, but for those, 'compiling' is just 'copy them over'.

Then, you can read them using this syntax*:

class Example {
    public String readTextTxt() {
        try (InputStream in = Example.class.getResource("text.txt")) {
            return new String(in.readAllBytes(), StandardCharsets.UTF_8);
        } catch (IOException | NullPointerException e) {
            throw new ClassDefNotFoundError("Missing resource: text.txt", e);
        }
    }
}

If the files are not intended to be read-only, then usually 'the directory the war files go' is not the right place to put these - that's because this directory should be restricted (few to no users should be able to write to this directory, and the process itself should definitely not be able to write to this directory), which is problematic for files intended to be written to.

*1) This assumes test.txt is in the same place that Example.class lives; in the same jar file / classpath dir, and in the same 'package'. You can prepend a slash to search relative to the root of the jar file / classpath dir instead, and you can include subdirectories if you want.

*2) InternalError is appropriate: This file missing is as bad as one of your class files having been removed from the jar. If one were to molest your jar in such a fashion, NoClassDefFoundError would also occur.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72