I'm trying to use a local file in which I've specified my db connection properties which is named dao.properties. And I'm proceeding this way:
InputStream fichierProperties = classLoader.getResourceAsStream( "/src/dao/dao.properties" );
However, when using this path, I'm getting an exception stating that the debugger wasn't able to find that file.
Here are some packages in my project:
The dao.properties is just under the dao package.
How do I resolve this, please?
If you put the file inside the src folder, the IDE probably is packaging, when instructed to compile and build, the file into the bundled generated jar. So you can reach with the method GetResourceAsStream.
So if you put the file (dao.properties) in root folder of your sources files (generally the src folder), just simple referring to dao.properties will refer to the resource.
If you put the file inside a subfolder of src, the correct way to reference it would be subfolder/dao.properties.
The first "/" is not necessary as the getResourceAsStream always search in the classpath, that for default is the root of the sources folder, inside the jar. (where are not talking about external files!)
Updated:
Assuming you place a file name notes.txt inside a folder(package) named ´sub´, this is valid example, only for purporses of how to get a bundled file that is in jar.
public class Main {
public static void main (String[] args) throws IOException {
InputStream is = Main.class.getResourceAsStream("sub/notes.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
while (s != null) {
System.out.println (s);
s = br.readLine();
}
is.close();
}
}
I add more information about this, by referring to this post
Related
im Working on a project that can compile/run existing java files in PC.
most of code works pretty well, but im having a problem at getting the path of java files.
here are the problematic codes
void uploadJ() {
System.out.print("Insert File name : "); //ex)HelloWorld.java
FileName = sc.next();
}
void Compile(){
String s = null;
File file = new File(FileName);
String path = file.getAbsolutePath();
try {
Process oProcess = new ProcessBuilder("javac", path).start();
BufferedReader stdError = new BufferedReader(
new InputStreamReader(oProcess.getErrorStream()));
while ((s = stdError.readLine()) != null) {
FileWriter fw = new FileWriter(E_file, true);
fw.write(s);
fw.flush();
fw.close();
}
} catch...
}
For instance, when i put HelloWorld.java as a file name,
the absolute path of the HelloWorld.java should be C:\Users\user\eclipse-
workspace\TermProject\src\HelloWorld.java,
but instead, the result is C:\Users\user\eclipse-
workspace\TermProject\HelloWorld.java.
it misses /src/ so it always ends up with javac: file not found error.
When your application has been compiled, there will be no src directory. This working directory could also be set to anything.
You also can't guarantee that the file you are looking for is an actual file, in the context of a jar file, it isn't.
However, you can load files from the classpath. You can make use of Class#getResourceAsStream(String):
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class.`.
Finding the file can be accomplished by calling this.getClass().getResourceAsStream("/" + FileName), with the / causing the search to occur from the resource root.
To use this with javac, you'll have to create a temporary file and populate it with the data stream you get from getResourceAsStream.
I have 2 projects. Project A and Project B.
Inside Project A i have a class MyClass that has a method say: readMyFile() which reads a file from some xyz path.
Now I am trying to call readMyFile() from a class in Project B. And I get the error stating the file being attempted to be read does not exist.
How can I make sure that the file that is being read by readFile() in MyClass in Project A, is also visible in Project B ?
Comment to expanded answer:
Don't read jar resources a a File. That's probably your first problem, if that's what you are doing. Read it as a resource (via URL) with getClass().getResourceAsStream() or one of it's variants. Second, I wouldn't try to read files directly from A using paths dependent on jar B. Instead just create a class in project B that will serve up its resources. And just call that class/method from project A
For example
ProjectB
src
resources
images
background.png
text
stackoverflow.txt
mypackage
ResourceFinder.java
ResourceFinder.java
public class ResourceFinder {
public static final String BACKGROUND_IMG = "background.png";
public static final Sting STACKOVERFLOW_TXT = "stackoverflow.txt";
// maybe you'll want to do some try/catching null checks
// I'm being lazy
public static BufferedImage getImage(String fileName ) throws Exception {
URL url = ResourceFinder.class.getResource("/images/" + fileName);
BufferedImage image = ImageIO.read(url);
return image;
}
public static InputStream getTextFile(String file) throws Exception {
InputStream is = ResourceFinder.class.getResourceAsStream(
"/text/" + fileName);
return is;
}
}
Then in your Project A, you could just do something like
BufferedImage image = ResourceFinder.getImage(ResourceFinder.BACKROUND_IMG);
or
InputStream is = ResourceFinder.getTextFile(ResourceFinder.STACKOVERFLOW_TXT);
BufferedReader reader = new BufferedReader(new InputStreamReader(is);
Keep in mind that when you use File or any of its FileXxx variants, you are reading from the file system. So any hard coded path you use may not work, once the file is "jarred", because the location is no longer the same. Thats why we read it via an URL, either with Class.getResource() which returns a URL or Class.getResourceAsStream() which returns an InputStream, using an URL under the hood. There are other variants using ClassLoader also. See the Class and ClassLoader Apis for other variants.
So my tomcat webapps directory looks like this:
C:/tomcat/webapps/myApp/
myApp/
resources/...
META-INF/
MANIFEST.MF
maven/
my.package.name/
myApp/
pom.properties
pom.xml
WEB-INF/
classes/...
lib/...
web.xml
I have an AppConfig.java (java spring config) where I am trying to get the pom.xml file so I can get certain things out of it. I have tried many things but have been unsuccessful in getting the file. I have a bean that I have just been putting a breakpoint in and trying different things to get the file.
#Bean
public String clientVersion()
{
BufferedReader reader = new BufferedReader(new InputStreamReader(ClassLoader.class.getResourceAsStream("/pom.xml")));
return "";
}
I have tried ClassLoader.class.getResourceAsStream() with many different paths though from what I have been able to find in other posts and forums ClassLoader.class.getResourceAsStream("META-INF/maven/my.package.name/myApp/pom.xml") should work, but I get null no matter what I do. Any suggestions?
To load resource you have to provide full path not only filename. Eg /maven/mypackage/myapp/pom.xml
Try with opening stash.
Change the code to:
#Bean
public String clientVersion()
{
BufferedReader reader = new BufferedReader(new InputStreamReader(ClassLoader.class.getResourceAsStream("/META-INF/maven/my.package.name/myApp/pom.xml")));
return "";
}
Depending on how it's stored on you file system, the my.package.name might need to actually be my/package/name.
Don't use the ClassLoader class, because you're probably picking up the wrong classloader (confusing, right?!).
Instead use my.package.name.MyClass.class.getResourceAsStream("/META-INF/maven/my.package.name/myApp/pom.xml")));, this way you can ensure both files (the class and the pom.xml) are available with the same classloader, since the are in the same archive.
I do this to get it as a String (inside a class called ServerResource.java, so swap in your class name):
InputStream is = ServerResource.class.getResourceAsStream("/META-INF/maven/org.buffalo/platform/pom.xml");
String pom = getStringFromInputStream(is);
if you extract your war/jar, you can confirm the path to the pom (for me it's META-INF/maven/org.buffalo/platform_ws/pom.xml)
Class::getResourceAsStream loads resources from the classpath; in a web application, that means files inside WEB-INF/classes, or inside one of the JAR files inside WEB-INF/lib. Your POM file isn't in either of those places, so it's not on the classpath.
Rather, being somewhere under the WAR root, it's a web resource, rather than a classpath resource. You can load web resources using ServletContext::getResourceAsStream.
Your code should look like:
#Bean
public String clientVersion(ServletContext servletContext) throws IOException {
String pomPath = "/META-INF/maven/my.package.name/myApp/pom.xml";
try (InputStream pomStream = servletContext.getResourceAsStream(pomPath)) {
BufferedReader reader = new BufferedReader(new InputStreamReader(pomStream));
return "";
}
}
I'm in troubles with opening file within my web-app. I tried it locally within Eclipse and it works fine but when I try to deploy it on Tomcat 6 on Openshift it doesn't find resource files for my web-app. There are some txt files in a ProjectFiles directory stored in WEB-INF directory; the code that locally opens file is
String nome_file = "C\:\\Users\\miKKo\\workspace\\fantacalcio_project\\WebContent\\WEB-INF\\ProjectFiles\\Risultati\\risultati_" + nome_lega + ".txt";
BufferedReader reader = new BufferedReader(new FileReader(nome_file));
I've pushed them within Git in the same repository (on server I renamed my project in "ROOT") and I've substituted string with this
String nome_file = this.getServletConfig().getServletContext().getContextPath()+"/WebContent/WEB-INF/ProjectFiles/Risultati/risultati_" + nome_lega + ".txt";
but it doesn't work. I've also tried with a context attribute
/var/lib/openshift/51c6178a5004467630000019/jbossews/work/Catalina/localhost/_/WEB-INF/ProjectFiles
but the thrown exception is always
java.io.FileNotFoundException: (#path) (No such file or directory)
What can I do for this?
Say your file is in the following location:
/WEB-INF/ProjectFiles/Risultati/risultat_text_file.txt
Then using:
String path = "/WEB-INF/ProjectFiles/Risultati/risultat_text_file.txt";
InputStream inputStream = new FileInputStream(this.getServletConfig().getServletContext().getRealPath(path));
Should work for you. Note that, ServletContext.getRealPath() return the real OS path corresponding to the given virtual path.
Edit:
If this doesn't work for your case, you really need to revisit your virtual path. You can manually check that does this file exist in the expected directory in the war file or you can log the output of the getRealPath() method to examine what's really going on! If necessary you can put "/" in your getRealPath() method and examine what is your application's root path.
Since I don't get application's root realpath, I resolved in this way:
String path="/WEB-INF/ProjectFiles/Risultati/risultati_test.txt";
InputStream inputStream = this.getServletConfig().getServletContext().getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
and now it works. By the way, I also found useful informations here
getResourceAsStream() vs FileInputStream
I have a Java EE 5 project in Eclipse (actually, IBM RAD 7) running on WebSphere 7.
The workspace projects are laid out like this:
webapp <-- produces a WAR file
webappEAR <-- produces the EAR file
webappEJB <-- holds the Service and DAO classes
webappJPA <-- holds the domain/entity classes
webappTests <-- holds the JUnit tests
In one of my Service classes (in the webappEJB project) I need to load a text file as a resource.
I placed my text file in folder:
webappEAR/emailTemplates/myEmailTemplate.txt
So it appears in the EAR file here:
webappEAR.EAR
/emailTemplates/myEmailTemplate.txt
In my service class this is how I load it:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("emailTemplates/myEmailTemplate.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(input));
/* and so on */
The problem is input is always null -- it can't find the resource.
I tried a leading slash ("/emailTemplates/myEmailTemplate.txt") but that didn't work either.
Any ideas what I'm doing wrong? Or a better way to do this?
Thanks!
Rob
The EAR file hierarchy/content is not on your classpath; Jar files packaged within your EAR file may be on a module's classpath, per configuration.
So package the resource into any of the JAR files already on the classpath of of the module containing your "service class".
It's not unreasonable to create a new JAR for resources, particularly if you'll be updating them independently.
That code seems ok, in JBoss that works as a charm. It may happen that the class loader form the Thread class has a different classpath than the ear file.
Did you try using the same class you are coding to load the resource?
Try something like this:
ClassInsideEar.class.getResourceAsStream("/emailTemplates/myEmailTemplate.txt");
You may also try placing the folder inside the war or jar (EJB) to narrow down the issue.
I used this code for loading resources from ear.
Path is folder/file. Location of file is resources/folder/file.
private InputStream loadContent(String path) {
final String resourceName = path;
final ClassLoader classLoader = getClass().getClassLoader();
InputStream stream = null;
try {
stream = AccessController.doPrivileged(
new PrivilegedExceptionAction<InputStream>() {
public InputStream run() throws IOException {
InputStream is = null;
URL url = classLoader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
is = connection.getInputStream();
}
}
return is;
}
});
} catch (PrivilegedActionException e) {
e.printStackTrace();
}
return stream;
}