Path to a file inside a package - java

Is there a way to read a text file which is inside a package.
Lets say that I want to access a file called "myTextFile.txt", which is in a package called "a".
I want to access it from a class called "MyClass" which is in the same package.
What would be the path to "myTextFile.txt"? And would I be able to use bufferedreader like this: BufferedReader in = new BufferedReader(new FileReader(PATH));

Where is your project compiled to? Any paths will be relative to the program's location, or the full path if you specify, not the class. Once you get that path you can put it where PATH is.
However, is there any reason you're putting that file inside a package? Shouldn't it go in some sort of resources directory?

GetResource on Class works well. ResourceLocator in Spring is also a very flexible option as well.

You can get always get resources via ClassLoader.getResourceAsStream() (or getResource()). They can also be accessed via Class.getResourceAsStream() (instead of ClassLoader). You could either use relative or absolute names (starting with /).

It sounds like you need to use one of the Class.getResource() or ClassLoader.getResource() methods:
URL url = MyClass.class.getResource("myTextFile.txt");
URL url = MyClass.class.getClassLoader().getResource("myTextFile.txt");
or
InputStream in = MyClass.class.getResourceAsStream("myTextFile.txt");
InputStream in = MyClass.class.getClassLoader().getResourceAsStream("myTextFile.txt");
See this question for a comparison, and an explanation of absolute versus relative paths.
Then you could do
new BufferedReader(new InputStreamReader(in));

InputStream is = new BufferedInputStream(
getClass().
getClassLoader().
getResourceAsStream("/a/myTextFile.txt"));
Should do the trick. Note please the structure of the arg, the root of the package is represented by "/" and so are your packages (i.e. directories)

Just input the absoulte file path. i.e. your lcoal machine path. Should work.

Related

The use of getResourceAsStream for BufferedReader and InputStream

I am writing webApp that use jsp file to call java class directly to get results.
The JSP file is like:
<%
String queryKey = request.getParameter("id");
int jobID = Integer.parseInt(queryKey);
out.println(jobID);
ArrayList<Integer> myTopList = JobRecByBoWJaccard.topJobsByBoW(jobID);
%>
In java classes the files are accessed through:
BufferedReader br = new BufferedReader(new FileReader("WebContent/StopWords/stop-words-english1.txt"));
and
private InputStream modelInputT = new FileInputStream("WebContent/OpenNLP_Models/en-token.bin");
The tomcat cannot find the referenced files and someone said use getResourceAsStream, but that is for servlets. I call the java class directly without any servlets.
private InputStream modelInputT = = this.getClass().getClassLoader().getResourceAsStream("WebContent/OpenNLP_Models/en-token.bin");
This cause java class cannot find the file as well. Need help and how to make changes to these java classes?
The tomcat cannot find the referenced files ...
That is because the pathnames are incorrect unless the JVM's current directory is the parent directory of the "WebContent" directory. When you use FileInputStream to open a file, relative pathname are resolved relative to the current directory of the JVM when it was launched.
... and someone said use getResourceAsStream, but that is for servlets.
No. That's not correct either. That method is not "for servlets". The purpose of that method is to open a resource that is on the class / classloader's classpath. If your "WebContent/StopWords/stop-words-english1.txt" is in the webapp's "/WEB-INFO/classes" or in a JAR file in "/WEB-INFO/lib", then getResourceAsStream will find it.
In your case, it seems like you are talking about the "WebContent" directory that corresponds to the default servlet.
In that case, read this Q&A - How can I get real path for file in my WebContent folder?.
So if you are trying to access those files from within a JSP, it seems as if you should be writing this:
new FileReader("WebContent/StopWords/stop-words-english1.txt")
as this:
new FileReader(getServletContext().getRealPath(
"/StopWords/stop-words-english1.txt"))

FileInputStream and FileNotFound Exception

I am trying to retrieve a jrxml file in a relative path using the following java code:
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
File report = new File(jasperFileName);
FileInputStream fis = new FileInputStream(report);
However, most probably I didn't succeed in defining the relative path and get an java.io.FileNotFoundException: error during the execution.
Since I am not so experienced in Java I/O operations, I didn't solve my problem. Any helps or ideas are welcomed.
You're trying to treat the jrxml file as an object on the file-system, but that's not applicable inside a web application.
You don't know how or where your application will be deployed, so you can't point a File at it.
Instead you want to use getResourceAsStream from the ServletContext. Something like:
String resourceName = "/WEB-INF/reports/MemberOrderListReport.jrxml"
InputStream is = getServletContext().getResourceAsStream(resourceName);
is what you're after.
You should place 'MemberOrderListReport.jrxml' in classpath, such as it being included in a jar placed in web-inf\lib or as a file in web-inf\classes.
The you can read the file using the following code:
InputStream is=YourClass.class.getClassLoader().getResourceAsStream("MemberOrderListReport.jrxml");
String jasperFileName = "/web/WEB-INF/reports/MemberOrderListReport.jrxml";
Simple. You don't have a /web/WEB-INF/reports/MemoberOrderListReport.jrxml file on your computer.
You are clearly executing in a web-app environment and expecting the system to automatically resolve that in the context of the web-app container. It doesn't. That's what getRealPath() and friends are for.
check that your relative base path is that one you think is:
File f = new File("test.txt");
System.out.println(f.getAbsoluteFile());
I've seen this kind of problem many times, and the answer is always the same...
The problem is the file path isn't what you think it is. To figure it out, simply add this line after creating the File:
System.out.println(report.getAbsolutePath());
Look at the output and you immediately see what the problem is.

Create a java file inside a package

Currently, my plugin creates a java file in my project(IProject). But I want that java file within a specified Package. How to do it.
IFile sampleFile = parentFolder.getFile("Sample.java");
if(!sampleFile.exists()) FileInputStream fileStream = new FileInputStream("C:\Users\Uma\Desktop\treasureHunt\Application.java"); sampleFile.create(fileStream, false, null);
This is my current piece of code.
How can I create the sampleFile within a package. For example: in package com.mdh.se as com.mdh.se.Sample.java
If you have a "package" (e.g. "com.mdh.se") then you'll have a corresponding subdirectory (for example, "c:\users\uma\desktop\treasurehunt\com\mdh\se"). Simply write your file there.
I think, that the only thing you need to do is to create folders representing your package structure. So your path should look like C:\Users\Uma\Desktop\treasureHunt\com\mdh\se\Sample.java for your example.
You can get a special file inside the package by calling
java.net.URL imgURL = ResourceManager.class.getResource( "ResourceManager.class" );
From these URL you can extract the directory, the file is placed.
A new file you can create with
new File(directory,filename);

getResource with parent directory reference

I have a java app where I'm trying to load a text file that will be included in the jar.
When I do getClass().getResource("/a/b/c/"), it's able to create the URL for that path and I can print it out and everything looks fine.
However, if I try getClass().getResource(/a/b/../"), then I get a null URL back.
It seems to not like the .. in the path. Anyone see what I'm doing wrong? I can post more code if it would be helpful.
The normalize() methods (there are four of them) in the FilenameUtils class could help you. It's in the Apache Commons IO library.
final String name = "/a/b/../";
final String normalizedName = FilenameUtils.normalize(name, true); // "/a/"
getClass().getResource(normalizedName);
The path you specify in getResource() is not a file system path and can not be resolved canonically in the same way as paths are resolved by File object (and its ilk). Can I take it that you are trying to read a resource relative to another path?

classloader.getSystemResourceAsStream returns null

I'm trying to load a properties file without using the actual path of the file. I've already done that on some other simple apps using:
InputStream inputStream = ClassLoader.getSystemResourceAsStream(PROPERTIES_FILE);
props.load(inputStream);
But this time it doesn't work. The inputStream is null for some reason. PROPERTIES_FILE is a constant defined as "app.properties". I tried to remove the .properties extension and got the same results.
Any ideas?
Thanks.
The PROPERTIES_FILE constant should include the package as well as the properties file (e.g. "com/some/library/file.properties".
final static String PROPS_FILE = "/com/some/library/file.props";
//The preceding "/" is dependendant on wheterh
//you are going to be giving a relative or absolute location
InputStream is = YourCurrentClass.class.getResourceAsStream(PROPS_FILE);
Got the same problem.
Reason: I renamed DAO package to dao. While exploding the artifact, directory DAO not get overwritten.
So I got dao in project internals and DAO in filesystem :facepalm:
When getSystemResourceAsStream returns null, it means the resource was not found. Make sure the requested resource really is on the classpath at the specified location.

Categories

Resources