I am pretty new to Maven, and having some trouble reading files. Specifically, my program takes the absolute path of a file as input from the user, and then parses it. Unfortunately I am unclear on how to get my application to read a file as input from an arbitrary location.

Before I started using maven on the project, I used this code successfully:

String absolutePath = "/Users/akhalsa/path/to/file.txt";
inputStream = new BufferedReader(new FileReader(absolutePath));

However, since migrating to maven, this seems to have stopped working. From what I have read in maven I should use

InputStream in = getClass().getResourceAsStream(filePath);

Where filePath seems to be the relative path of the file in question. Does getResourceAsStream require that the file being read be inside the jar? Can this file be an external file's absolute path? When I use an absolute path here it says "Resource not found".

This must be a common problem in terms of letting users input a file from the file system for a maven application to process. What is the best way to this?

Thanks in advance.

有帮助吗?

解决方案

getResourceAsStream() finds the resource on a path known to the jvm, so you can't load arbitrary files.

Maven does no magic trickery so if you are using actual absolute paths, the code should keep on working.

The "Users" part of the path reminds me of windows, but the path is not a valid windows path so are you sure you are passing along a valid absolute path?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top