I have a java application project in Netbeans. I have just one class.
I try to do this
FileReader fr = new FileReader("sal.html");
I have the file sal.html under the same package. But I get this error when I run:
Errorjava.io.FileNotFoundException: sal.html (The system cannot find the file specified)
My guess is that Netbeans is invoking the JVM from your project's root folder. Quoting a portion of the File Javadoc:
By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.
To verify relative path resolution you could try:
System.out.println(System.getProperty("user.dir"));
System.out.println(new File("sal.html").getAbsolutePath());
You could then move your file to wherever java is looking for it. Most probably your project's root folder.
You could also consider using the class loader to read files as resources inside packages using getClass().getResourceAsStream("sal.html");. This is the preferred way of accessing resources since you no longer have to worry about absolute vs. relative paths. If a resource is in your classpath, you can access it. See this answer for more.
Put your file to main project folder. Not to any sub folders like src, or bin etc. Then it will detect your file.
Click on file view in Netbeans. Move sal.html to the project folder. Such that you will see it like this
- JavaProject
+ build
+ lib
+ nbproject
+ src
+ build.xml
manifest.mf
sal.html
Now
FileReader fr = new FileReader("sal.html");
will work.
System.out.println(System.getProperty("user.dir"));
System.out.println(new File("sal.html").getAbsolutePath());
Then it will show where the JVM is retrieving the files from. Usually for linux in the /home/username/NetbeansProjects/ApplicationName/.
Put your resources or files to this path
I think your problem is in the relative path to the file. Try to declare FileReader with full path to file.
FileNotFoundException means file not found.
The build folder for the netbeans is different where there is no file sal.html.
Try using absolute path in place of using relative path.
This is not a "File not found" problem.
This is because each class hold its own resources (let it be file, image etc.) which can be accessed only through a resource loader statement which is as below:
InputStream in = this.getClass().getResourceAsStream("sal.html");
The only fix is that you will get an InputStream instead of a file.
Hope this helps.
Related
I have a maven project with these standard directory structures:
src/main/java
src/main/java/pdf/Pdf.java
src/test/resources
src/test/resources/files/x.pdf
In my Pdf.java,
File file = new File("../../../test/resources/files/x.pdf");
Why does it report "No such file or dirctory"? The relative path should work. Right?
Relative paths work relative to the current working directory. Maven does not set it, so it is inherited from whatever value it had in the Java process your code is executing in.
The only reliable way is to figure it out in your own code. Depending on how you do things, there are several ways to do so. See How to get the real path of Java application at runtime? for suggestions. You are most likely looking at this.getClass().getProtectionDomain().getCodeSource().getLocation() and then you know where the class file is and can navigate relative to that.
Why does it report "No such file or dirctory"? The relative path should work. Right?
wrong.
Your classes are compiled to $PROJECT_ROOT/target/classes
and your resources are copied to the same folder keeping their relative paths below src/main/resources.
The file will be located relative to the classpath of which the root is $PROJECT_ROOT/target/classes. Therefore you have to write in your Pdf.java:
File file = new File("/files/x.pdf");
Your relative path will be evaluated from the projects current working directory which is $PROJECT_ROOT (AFAIR).
But it does not matter because you want that to work in your final application and not only in your build environment. Therefore you should access the file with getClass().getResource("/path/to/file/within/classpath") which searches the file in the class path of which the root is $PROJECT_ROOT/target/classes.
No the way you are referencing the files is according to your file system. Java knows about the classpath not the file system if you want to reference something like that you have to use the fully qualified name of the file.
Also I do not know if File constructor works with the classpath since it's an abstraction to manage the file system it will depend where the application is run from. Say it is run from the target directory at the same level as source in that case you have to go one directory up and then on src then test the resources the files and finally in x.pdf.
Since you are using a resources folder I think you want the file to be on the classpath and then you can load a resource with:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("<path in classpath>");
Then you can create a FileInputStream or something to wrap around the file. Otherwise use the fully qualiefied name and put it somewere like /home/{user}/files/x.pdf.
I've been trying to read and write to a file under my resources directory in my project. However, regardless of what I seem to do it doesn't allow me to do so.
This is my project hierarchy for reference:
Out of all these:
Paths.get("memes.txt")
Paths.get("resources/memes.txt")
Paths.get("/resources/memes.txt")
...
None have worked. What am I doing wrong?
Is it a Maven project ?
Try this :
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
Ref : https://www.mkyong.com/java/java-read-a-file-from-resources-folder/
Your application can be packed as .jar file - a zip format.
There, or in the built classes directory should be memes.txt. A so-called resource, and in case of a jar not really a file system file. But is located on the class path.
URL url = getClass().getResource("/memes.txt");
InputStream in = getClass().getResourceAsStream("/memes.txt");
The path is relative to the package directory of the class, or absolute as above.
Try it using "../resources/memes.txt" with ".." you go up one directory from your current file (i assume that you are using the code in SwearTest.java)
I have a folder called lib that contains all my Jar files and in one of the Jar files class, I have a main method which is called by a batch file. In the same folder location as my lib, I have another folder structure path/to/a/resource/myresource.txt
How can I load this file from a class inside the Jar file? I tried the following and both resulted in null:
getClass().getResource("path/to/a/resource/myresource.txt")
getClass().getClassLoader().getResource("path/to/a/resource/myresource.txt")
Any ideas? Even with an absolute path, it failed! Any suggestions?
You can use:
getClass().getResourceAsStream("path/to/a/resource/myresource.txt")
However, for this to work, you need to add the path '.' to the Class-Path entry of the JAR's MANIFEST.MF file.
http://docs.oracle.com/javase/tutorial/deployment/jar/downman.html
Two things you tried are used to read files from class-path since this folder is not on your classpath you can read it directly with any of the java File IO classes.
File file = new File("C:/folder/myFile.txt");
or if you know the relative path:
File file = new File("../../path/myFile.txt");
Your path seems not to be precise enough. Further, this question has been worked before.
Have a look here:
How to Load File Outside of, but Relative to, the JAR?
How to get the path of a running JAR file?
You can either load the file from file system
new FileReader(relativeOrAbsoluteFilesystemLocation)
or you can add the directory in question to your classpath:
java -cp "lib/*;lib" ...
and then use your original method.
(Unix uses : rather than ; as classpath separator)
I am using a method that requires a string path to a file that is in my src directory structure in eclipse. Is the path to this file simply src\fileName.txt or is there a different way i should be getting this file as it doesnt seem to be working currently
Thanks
Run this and you will never forget how to remember.
File file = new File("sample.txt");
System.out.println(file.getAbsolutePath());
If you are following the maven standard directory structure, class files will be located relative to the classpath like so:
If you want SomeClass.class, you would access it by com.mydomain.packageorappname.deeperpackage.SomeClass. Is that what you are asking?
In my Java app I need to get some files and directories.
This is the program structure:
./main.java
./package1/guiclass.java
./package1/resources/resourcesloader.java
./package1/resources/repository/modules/ -> this is the dir I need to get
./package1/resources/repository/SSL-Key/cert.jks -> this is the file I need to get
guiclass loads the resourcesloader class which will load my resources (directory and file).
As to the file, I tried
resourcesloader.class.getClass().getResource("repository/SSL-Key/cert.jks").toString()
in order to get the real path, but this way does not work.
I have no idea which path to use for the directory.
I had problems with using the getClass().getResource("filename.txt") method.
Upon reading the Java docs instructions, if your resource is not in the same package as the class you are trying to access the resource from, then you have to give it relative path starting with '/'. The recommended strategy is to put your resource files under a "resources" folder in the root directory. So for example if you have the structure:
src/main/com/mycompany/myapp
then you can add a resources folder as recommended by maven in:
src/main/resources
furthermore you can add subfolders in the resources folder
src/main/resources/textfiles
and say that your file is called myfile.txt so you have
src/main/resources/textfiles/myfile.txt
Now here is where the stupid path problem comes in. Say you have a class in your com.mycompany.myapp package, and you want to access the myfile.txt file from your resource folder. Some say you need to give the:
"/main/resources/textfiles/myfile.txt" path
or
"/resources/textfiles/myfile.txt"
both of these are wrong. After I ran mvn clean compile, the files and folders are copied in the:
myapp/target/classes
folder. But the resources folder is not there, just the folders in the resources folder. So you have:
myapp/target/classes/textfiles/myfile.txt
myapp/target/classes/com/mycompany/myapp/*
so the correct path to give to the getClass().getResource("") method is:
"/textfiles/myfile.txt"
here it is:
getClass().getResource("/textfiles/myfile.txt")
This will no longer return null, but will return your class.
It is strange to me, that the "resources" folder is not copied as well, but only the subfolders and files directly in the "resources" folder. It would seem logical to me that the "resources" folder would also be found under `"myapp/target/classes"
Supply the path relative to the classloader, not the class you're getting the loader from. For instance:
resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();
In the hopes of providing additional information for those who don't pick this up as quickly as others, I'd like to provide my scenario as it has a slightly different setup. My project was setup with the following directory structure (using Eclipse):
Project/
src/ // application source code
org/
myproject/
MyClass.java
test/ // unit tests
res/ // resources
images/ // PNG images for icons
my-image.png
xml/ // XSD files for validating XML files with JAXB
my-schema.xsd
conf/ // default .conf file for Log4j
log4j.conf
lib/ // libraries added to build-path via project settings
I was having issues loading my resources from the res directory. I wanted all my resources separate from my source code (simply for managment/organization purposes). So, what I had to do was add the res directory to the build-path and then access the resource via:
static final ClassLoader loader = MyClass.class.getClassLoader();
// in some function
loader.getResource("images/my-image.png");
loader.getResource("xml/my-schema.xsd");
loader.getResource("conf/log4j.conf");
NOTE: The / is omitted from the beginning of the resource string because I am using ClassLoader.getResource(String) instead of Class.getResource(String).
When you use 'getResource' on a Class, a relative path is resolved based on the package the Class is in. When you use 'getResource' on a ClassLoader, a relative path is resolved based on the root folder.
If you use an absolute path, both 'getResource' methods will start at the root folder.
#GianCarlo:
You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:
String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;
// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);
For those using eclipse + maven. Say you try to access the file images/pic.jpg in src/main/resources. Doing it this way :
ClassLoader loader = MyClass.class.getClassLoader();
File file = new File(loader.getResource("images/pic.jpg").getFile());
is perfectly correct, but may result in a null pointer exception. Seems like eclipse doesn't recognize the folders in the maven directory structure as source folders right away. By removing and the src/main/resources folder from the project's source folders list and putting it back (project>properties>java build path> source>remove/add Folder), I was able to solve this.
resourcesloader.class.getClass()
Can be broken down to:
Class<resourcesloader> clazz = resourceloader.class;
Class<Class> classClass = clazz.getClass();
Which means you're trying to load the resource using a bootstrap class.
Instead you probably want something like:
resourcesloader.class.getResource("repository/SSL-Key/cert.jks").toString()
If only javac warned about calling static methods on non-static contexts...
Doe the following work?
resourcesloader.class.getClass().getResource("/package1/resources/repository/SSL-Key/cert.jks")
Is there a reason you can't specify the full path including the package?
Going with the two answers as mentioned above. The first one
resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();
resourcesloader.class.getResource("repository/SSL-Key/cert.jks").toString()
Should be one and same thing?
In Order to obtain real path to the file you can try this:
URL fileUrl = Resourceloader.class.getResource("resources/repository/SSL-Key/cert.jks");
String pathToClass = fileUrl.getPath;
Resourceloader is classname here.
"resources/repository/SSL-Key/cert.jks" is relative path to the file. If you had your guiclass in ./package1/java with rest of folder structure remaining, you would take "../resources/repository/SSL-Key/cert.jks" as relative path because of rules defining relative path.
This way you can read your file with BufferedReader. DO NOT USE THE STRING to identify the path to the file, because if you have spaces or some characters from not english alphabet in your path, you will get problems and the file will not be found.
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileUrl.openStream()));
I made a small modification on #jonathan.cone's one liner ( by adding .getFile() ) to avoid null pointer exception, and setting the path to data directory. Here's what worked for me :
String realmID = new java.util.Scanner(new java.io.File(RandomDataGenerator.class.getClassLoader().getResource("data/aa-qa-id.csv").getFile().toString())).next();
Use this:
resourcesloader.class.getClassLoader().getResource("/path/to/file").**getPath();**
One of the stable way to work across all OS would be toget System.getProperty("user.dir")
String filePath = System.getProperty("user.dir") + "/path/to/file.extension";
Path path = Paths.get(filePath);
if (Files.exists(path)) {
return true;
}