maven read file input from user - java

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?

Related

Eclipse can't read text file in src folder

I am implementing a Branch Predictor for one of my classes and I am trying to read files from my src folder in Eclipse but for some reason it is not able to open the files. I have done this before with the exact same process so I'm not sure what is different.
traceFile is set from the command line and if I print "input", it will print out the correct file path and I have confirmed it is there manually.
ClassLoader loader = BiModalPredictor.class.getClassLoader();
File input = new File(loader.getResource(traceFile).getFile());
Scanner fin = new Scanner(input);
Is there any insight as to why this might be happening? I've tried restarting Eclipse, refreshing the files, and I've also tested it on another program which worked. No idea why it can't find this file.
Resources on the classpath, i.e. available through the classloaders getResource method, will not be files on the file system when your application is deployed as a jar file, or deployed in general. Do not use File with such resources, instead use getResourceAsStream to access the resource content.
Besides, your code is wrong. getResource() returns a URL. If you want a File object from a URL, you should use new File(uri), where the URI is obtained by calling url.toURI().
File input = new File(loader.getResource(traceFile).toURI());

System can't find path

Trying to practice Java by doing basic functionality like reading input.
I am trying to parse movies-sample.txt found in:
C:\University\BigDataManagement\Data-Mining\hw1\src\main\resources\movies-sample.txt
Trying to reach movies-sample.txt from
C:\University\BigDataManagement\Data-Mining\hw1\src\main\java
\univ\bigdata\course\MoviesReviewsQueryRunner.java
Using the answer found here on how to parse a large file line by line.
File file = new File("../../../../../resources/movies-sample.txt");
I am getting the following error:
The system cannot find the path specified
Given the above two paths, what am I doing incorrect?
If it's a web app then the resources folder is your root element, otherwise it will be the src folder as mentioned in comments.
In your case here as you are writing a standalone Java program and as your file is loacted in the resources folder, you can use CLassLoader to read the file as a stream.
This is how should be your code:
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("movies-sample.txt");
Then you will be able to read the is stream line by line.
If you run your program directly from command line, then the path must be related to your current directory.
If you run your program from an IDE, then the current directory of the runnin program depends on the IDE and the way it is configured.
You can determine what is the current directory with System.getProperty("user.dir")
Whatever, hard coding a path in an application is always a bad thing because you cannot ensure where the run was launched from. Either:
it is a user resource, then its path must be input in some way (open... in GUIs apps)
it is a resource needed by the app to run correctly and it should be embedded in some way into the app itself (look for Resource Bundle)
it is a kind of optional external resource (config file for example, or path specified in a config file) and its location should be computed in some way.

Absolute path of a file inside a project package

I've created a file inside a project package using this code:
File xmlFile = new File("src/com/company/project/xml/tags.xml");
I am able to read the file while running from eclipse. However, after creating .jar, I'm unable to read the file. So I want to put absolute path while reading the file from the project package. How it can be done? Help and suggestions are appreciated.
In most cases, IDE's will include no Java files in the resulting Jar. Most IDE's will also include the src directory in the classpath when you run/debug the program from within them.
As a general rule of thumb, never include src in any path, src will simply not exist once the program is built.
Instead you need to make use of Class#getResource or Class#getResourceAsStream, depending on your needs. You should remember, you should never treat an "embedded" resource as a File, as in most cases it won't be, it'll be a stream of bytes in a zip file.
Something like...
URL xmlFile = getClass().getResource("/com/company/project/xml/tags.xml");
will return a URL reference to the resource. Remember, if you need a InputStream, you'll have to Class#getResourceAsStream.
If you want the resource to be writable, then you will need to find a different location to store it, as embedded resources are read only
Try with getClass().getResource()
new File(getClass().getResource("src/com/company/project/xml/tags.xml").toURI());

Calling a path in java method

I have a small problem calling a path(that has the python file, that I need to run) in the following code:
Process p = Runtime.getRuntime().exec(callAndArgs,env,
new java.io.File("C:\\Users\\Balkishore\\Documents\\NetBeansProjects\\Testinstrument_Rest\\build\\web"));//excuting python file
As it can be seen from the above code, the python file is called using the path specified in java.io.file function. But it is very specific, as it can be run only in my computer. How can i make it generic, so that it is possible to run this piece of code in any computer?
Any help would be very much appreciated.
Put your python script to the location relative to your working directory and use relative path. Alternatively use configuration file or property to read the path from.
If this file is already exist in the app then you need to do
ServletContext.getRealPath("/");
which will give you the path to web root now from here you need to move relatively to reach to your file
If this is an external file
put it in ${user.home}/appname/
String filePath = System.getProperty("user.home")+File.separator+"APP_NAME"
and instruct your users to put the file in this path, or read the path from some configuration file (.properties, .conf)

What is the path to resource files in a Maven project?

In my Maven project, I have the following code in the main method:
FileInputStream in = new FileInputStream("database.properties");
but always get a file not found error.
I have put the file in src/main/resources and it is properly copied to the target/classes directory (I believe that is the expected behavior for Maven resources) but when actually running the program it seems it can never find the file. I've tried various other paths:
FileInputStream in = new FileInputStream("./database.properties");
FileInputStream in = new FileInputStream("resources/database.properties");
etc. but nothing seems to work.
So what is the proper path to use?
Based on "disown's" answer below, here was what I needed:
InputStream in = TestDB.class.getResourceAsStream("/database.properties")
where TestDB is the name of the class.
Thanks for your help, disown!
You cannot load the file directly like that, you need to use the resource abstraction (a resource could not only be in the file system, but on any place on the classpath - in a jar file or otherwise). This abstraction is what you need to use when loading resources. Resource paths are relative to the location of your class file, so you need to prepend a slash to get to the 'root':
InputStream in = getClass().getResourceAsStream("/database.properties");

Categories

Resources