I'm programming Java in Eclipse IDE. Here is code I want to read file:
File file = new File("file.txt");
reader = new BufferedReader(new FileReader(file));
I put file.txt in two place:
1) same folder of this SOURCE file.
2) in bin\...\ (same folder of this CLASS file)
But I allways receive NO FILE FOUND.
Please help me.
thanks :)
If the file ships with your application, it would be better accessed as a resource than as a file. Simply copy it to somewhere in your build path and use Class.getResourceAsStream or ClassLoader.getResourceAsStream. That way you'll also be able to access it if you bundle your app as a jar file.
Currently, you're looking for the file relative to the process's current working directory, which could be entirely unrelated to where the class files are.
if you put the file under sources and inside the package "test" for example, the path is:
./src/test/file.txt
you can use
File file = new File("./src/test/file.txt");
System.out.println(file.exists());
The path ./bin/test/file.txt will work in the second case and is more suitable for a normal java project
Related
I am currently working on a Java application in Intellij, and I cannot create a file within my artifact. As an example, I'm using File to create a file within the source, which is MainMenuData.txt.
File mainMenu = new File("MainMenuData.txt");
String absPath = mainMenu.getPath();
mainMenu.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(absPath));
In this, I'm using File to make sure that file exists whenever it isn't.
Instead, I'd like to build within the (Production) artifact. Is that doable?
Anything helps. Thanks.
You could do that.
I assume your artifact is a jar file, which is nothing else than a zip file. You can obtain the location of your jar file in the file system and use the Zip File System to modify it. However I'm not sure, if the jvm might have a problem with that and it might not work on windows, since windows likes to block files, that are in use.
Also this would definitely fail, if your jar file is not stored locally.
A better approach would be to store your data files at the appropriate location in your system.
On Linux(and probably mac): <home>/.local/share/<your application name>/
On Linux(global): /var/lib/<application name>
On Windows(I think, better check it yourself): <appdata>/<your application name>
Your code would look something like this(for Linux):
File home = new File(System.getProperty("HOME");
File configDirectory = new File(home, ".local/share/<application name>");
configDirectory.mkdirs();
File mainMenu = new File(configDirectory, "MainMenuData.txt");
For windows do something similar. If you need both, you should check on which you are currently running.
I am making an application where I have to read text-files in order to make my program work. When I run this application in InteliJ it runs perfectly but when I make a .jar file I get a "no such file exception".
Can someone explain me how to access my files inside a .jar file from a class inside the same .jar file?
Can someone also tell me which type of path is more preferable to use (Absolute or relative)?
NOTE: the purpose of the program is to help friends to learn basic words in Arabic. This means that the .jar file will be moved from one computer to the other and it still has to work.
By the way, is putting everything into a .jar something good or are there better ways to put my project in one executable file?
Image of my directory structure
The code i use is:
Path path = Paths.get("src/Multimedia/Woordenschat/Boek1/Arabisch/Hoofdstuk 1.txt");
You can use a BufferedReader and get the file stream with getResourceAsStream():
InputStream in = getClass().getResourceAsStream("path");
BufferedReader input = new BufferedReader(new InputStreamReader(in));
I'm trying to read a txt file that is in a folder called "levels". The class where I'm using the Scanner is in src/anotherPackageName, if that's relevant. When I execute:
Scanner s = new Scanner(new File("levels/level0")); //adding .txt doesn't fix
it throws an exception. I don't want to use an absolute path, but rather relative to the project if possible. This is my folder structure:
D:\OneDrive\Folder\AnotherFolder\ProjectName
ProjectName
src
packageOne
ClassWhereImUsingScanner
OtherClasses
(...)
levels
level0
level1
(...)
So in order to access a file you could do something like this:
FileReader sourceFile = new FileReader("levels/level0.txt");
BufferedReader inStream = new BufferedReader(sourceFile);
String Line = inStream.readLine();
Then, you can use a tokenizer depending on your data and how you want to store it.
You could see this example: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Bear in mind that in most Java code, the end state of the project is not run from the IDE, but rather from some production system (e.g. an app or a server). In that case, your development source code structure won't be available.
There are two main ways to read text files or other resources in Java: either you can find the path to the actual file, in which case you need to deal with possibly not running out of your development source tree, or else you need to find a way to bundle the text file into your project.
Most Java projects end up getting compiled into some kind of archive, either a JAR file or a WAR file (for web applications) or something like an Android APK. In most cases you can add your own text files into the project archive. (For example, in a Maven project, if you just put your text file in the src/main/resources folder it should be included in the compiled JAR.)
However, in this case, the text file is no longer a separate file on disk, but rather a blob of data inside an archive. You could unzip the archive to get an actual File object, but that's wasteful if all you actually need is to read the bytes.
Thus, the most common way that text files like this are read is by using the existing ClassLoader mechanism, which is what is reading the .class files from disk (or from an archive, or over the network, or whatever). The ClassLoader already knows how to load bytes that are "alongside" your compiled code, so you can just make use of that.
In your case, you should be able to do something like this:
Scanner scanner = new Scanner(
getClass().getResourceAsStream("/path/to/file.txt"));
In this case, the /path/to/file.txt path is relative to the path your class was loaded from. E.g. if your class is named my.package.Foo then the actual class bytes will be in a folder (either a filesystem folder or in a JAR file or something) named my/package/Foo.class -- in this case, the path/to/file.txt and my/package/Foo.class will be relative to the same root.
See the documentation on resources for more information.
Usually the path is relative to your execution, but it also depends on your project setup on eclipse, could you send more information about you directory structure?
Based on you structure try something like this:
Scanner s = new Scanner(new File("../levels/level0"));
I know that there are many questions like this out there, but so far there have been none that have been of help.
In eclipse, I have a file inside of my project folder ,and I can get it to load using:
BufferedReader in = new BufferedReader(new FileReader(new File(path)));
When I export the project it will not load the file because it cannot find the file. I have no idea what is going on. Any suggestions? Thanks.
If you want to read the file, you have two options.
You Could...
Make sure that the file is in the same directory as the exported jar file and/or the same execution context. This will allow you to use something like BufferedReader in = new BufferedReader(new FileReader(new File("./" + fileName)));
When referencing the file, it need to specify a relative path to the file.
This means you must ensure that the file is copied to the correct location when ever you move the jar file.
You Could...
Embed the file within the jar as an embedded resource. This means that the file becomes part of the jar file. This also means that you can no longer reference it as a File, but need to use Class#getResource or Class#getResourceAsStream, for example...
BufferedReader in = new BufferedReader(
new InputStreamReader(this.getResourceAsStream("/path/to/resource")));
In order to use this, the file must be placed within the resources directory within your Eclipse project and the directory included within your build path
If you want to be able to write to the file, then you MUST use option one. Embedded resources can not be written to (without a lot of work)
I have a file holding default information that I use to load the textFields of my application. I looked up how to get this built into my jar file when I build and I was told to put it in the source packages and it would be brought along, so I have done that.
File Structure:
Project
-Source Packages
-src
~Java Classes
-defaultFiles
~Defaults.txt
The code I am trying to use is this:
BufferedReader in;
try {
URL resourceURL = FuelProperties.class.getResource("/defaultFiles/Defaults.txt");
in = new BufferedReader(new FileReader(resourceURL.getPath()));
}
And this works perfectly when I run it through NetBeans but when I build the project and try to run it from the jar file it is not grabbing the file.
I have verified that the default file is being built and exists in the same file structure shown above.
If you can help me out with this I would be extremely grateful as I have no idea what is keeping this from working. Thanks.
You have to lookup in the classpath, not on the disk.
The API to use is :
URL resourceURL : this.getClass().getResource("relative path in the classpath");
Once you have the url you can open a stream, etc.
EDIT : in the main method, you of course need to replace
this.getClass()
by
ClassName.class
I found the answer after searching through a couple dozen questions. It turns out that you can only get a InputStream of the data within a file within your JAR not a File object like I was attempting to do.
(If you want the File object you just have to extract the files from the JAR in your program and then you have access to it.)
So the code that got my problem to work was simply replacing this:
URL resourceURL = FuelProperties.class.getResource("/defaultFiles/Defaults.txt");
in = new BufferedReader(new FileReader(resourceURL.getPath()));
With this:
in = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/defaultFiles/Defaults.txt")));
And now it is working both inside NetBeans and in the Built JAR file.