Read a file places in same dir as class? - java

reader = new CSVReader(new FileReader("file.txt"));
The file is placed in the same directory as the java class. Anyhow I get FileNotFoundException.
What is wrong?

Relative paths are relative to the current working directory. In your code sample, if file.txt isn't in your current directory, it won't be found.
Be wary of using relative paths in your code. That's because it's impossible to tell at compile time what the current working directory will be when your code is run.
If the file is part of your deployment, store it on the classpath and access it via ClassLoader.getResourceAsStream(), if it's truly external data that the user can change, put the file name in a configuration of some sort.

File needs to be in the root folder of the project.

Your application doesn't run in that directory. You would either have to use an absolute (or classpath-relative) path, or move the file to the directory where the application runs. In Eclipse, for example, this would be the root folder of your project.

Related

Using relative path in a maven project

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.

Java can't read file except when in project root directory

I am using IDEA 14 to follow a simple Java tutorial (JDBC). As part of this, I am storing some configuration properties in a file called jdbcTutorial.properties. When I put this in the root directory of the project, I can read it with the following:
Properties props = new Properties();
props.load(new FileInputStream("jdbcTutorial.properties"));
However, as soon as I move it to any other directory in the project, I get the error "No such file or directory". This happens regardless of whether I specify a relative or absolute path:
Maybe there are more standard ways to use config files, but I would really like to understand the behavior I am observing. Thanks for helping!
By default root directory would be added to your project's build path. Since the directory in which you are putting the file is not added in your project's build path jvm is unable to find the file. You have two options:
Add the folder where you are putting your prop to build path.
Access the file with full path i.e. /home/user/workspace/....
When you build a project, IDEA takes the files in the resources directory and puts them in the executable jar. So to get an input stream from that file, you need to get it directly from inside the jar. Instead of FileInputStream, use
getClass().getResourceAsStream("jdbcTutorial.properties")
When no path is supplied for a file, java assumes that this file is in the project's root folder. So the relative path "." always points to this folder. When the file is somewhere else, put the appropriate relative path before the path name, like "./files/configuration/jdbcTutorial.properties".
It work also when you put an absolute file path before the path name, like "C:/Users/Me/Documents/Java/workspace/thisProject/files/configuration/jdbcTutorial.properties".

Sharing a Java Object Stream

I've got a project to do with 2 other classmates.
We used Dropbox to share the project so we can write from our houses (Isn't a very good choice, but it worked and was easier than using GitHub)
My question is now about sharing the object stream.
I want to put the file of the stream in same dropbox shared directory of the code.
BUT, when i initialize the file
File f = new File(PATH);
i must use the path of my computer (C:\User**Alessandro**\Dropbox)
As you can see it is linked to Alessandro, and so to my computer.
This clearly won't work on another PC.
How can tell the compiler to just look in the same directory of the source code/.class files?
You can use Class#getResource(java.lang.String) to obtain a URL corresponding to the location of the file relative to the classpath of the Java program:
URL url = getClass().getResource("/path/to/the/file");
File file = new File(url.getPath());
Note here that / is the root of your classpath, which is the top of the directory containing your class files. So your resource should be placed inside the classpath somewhere in order for it to work on your friend's computer.
Don't use absolute paths. Use relative paths like ./myfile.txt. Start the program with the project directory as the current dir. (This is the default in Eclipse.) But then you have to ensure that this both works for development and for production use.
As an alternative you can create a properties file and define the path there. Your code then only refers to a property name and each developer can adjust the configuration file. See Properties documentation.

Java - read file from directory for jar

I have an application that creates a temporary mp3-file and puts it in a directory like C:\
File tempfile = File.createTempFile("something", ".mp3", new File("C:\\));
I'm able to read it by just using that same tempfile again.
Everything works fine in the Eclipse IDE.
But when I export my project for as a Runnable jar, my files are still being made correctly (I can play them with some normal music player like iTunes) but I can't seem to read them anymore in my application.
I found out that I need to use something like getClass().getResource("/relative/path/in/jar.mp3") for using resource files that are in the jar. But this doesn't seem to work if I want to select a file from a certain location in my file system like C:\something.mp3
Can somebody help me on this one?
It seems you dont have file name of the temp files . When you was running your program in eclipse that instance was creating a processing files, but after you made a runable you are not able to read those file that instance in eclipse created, You runable file can create its own temp file and can process them,
To make temp files globe put there (path + name ) entries in some db or property file
For example of you will create a temp file from the blow code
File tempfile = File.createTempFile("out", ".txt", new File("D:\\"));
FileWriter fstream = new FileWriter(tempfile);//write in file
out = new BufferedWriter(fstream);
the out will not be out.txt file it will be
out6654748541383250156.txt // it mean a randum number will be append with file
and you code in runable jar is no able to find these temp files
getClass().getResource() only reads resources that are on your classpath. The path that is passed to getResource() is, in fact, a path relative to any paths on your current classpath. This sounds a bit confusing, so I'll give an example:
If your classpath includes a directory C:\development\resources, you would be able to load any file under this directory using getResource(). For example, there is a file C:\development\resources\mp3\song.mp3. You could load this file by calling
getClass().getResource("mp3/song.mp3");
Bottom line: if you want to read files using getResource(), you will need those files to be on your classpath.
For loading from both privileged JARs and the file system, I have had to use two different mechanisms:
getClass().getClassLoader().getResource(path), and if that returns null,
new File(path).toURI().toURL();
You could turn this into a ResourceResolver strategy that uses the classpath method and one or more file methods (perhaps using different base paths).

FileNotFoundException in Netbeans

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.

Categories

Resources