Been looking for this for the past 2 hours and can't find anything (I've found solutions to the same problem but with images, not text files).
Pretty much, I made a program that reads a text file. The file is a list of names and IDs. Using Eclipse, I put the file in my src folder and in the program put the path file to it. Like this:
in = new BufferedReader(new FileReader(curDir+"\\bin\\items.txt"));
Where curDir is the user's current directory (found with System.getProperty("user.dir")).
Now, problem is, the program runs fine when I run it from Eclipse, but when I try to make it a runnable JAR and then run it, the program runs, but the info from the text file does not load. It look like Eclipse is not putting the text file with the JAR.
EDIT: Solved-ish the problem? So the JAR file needs to the in a folder with all the original files? I am so confused, what is a JAR file then?
A more robust way to get a file whether you are running from Eclipse or a JAR is to do
MyClass.getResource("items.txt")
where MyClass is a class in the same package (folder) as the resource you need.
If Eclipse is not putting the file in your JAR you can go to
Run -> Run Configurations -> -> Classpath tab -> Advanced -> Add Folders
Then add the folder containing your file to the classpath. Alternatively, export the Ant script and create a custom build script.
To the point, the FileReader can only read disk file system resources. But a JAR contains classpath resources only. You need to read it as a classpath resource. You need the ClassLoader for this.
Assuming that Foo is your class in the JAR which needs to read the resource and items.txt is put in the classpath root of the JAR, then you should read it as follows (note: leading slash needed!):
InputStream input = Foo.class.getResourceAsStream("/items.txt");
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
// ...
Or if you want to be independent from the class or runtime context, then use the context class loader which operates relative to the classpath root (note: no leading slash needed!):
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("items.txt");
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
// ...
(UTF-8 is of course the charset the file is encoded with, else you may see Mojibake)
Get the location of your jar file
Firstly create a folder(say myfolder) and put your files inside it
Consider the following function
public String path(String filename)
{
URL url1 = getClass().getResource("");
String ur=url1.toString();
ur=ur.substring(9);
String truepath[]=ur.split("myjar.jar!");
truepath[0]=truepath[0]+"myfolder/";
truepath[0]=truepath[0].replaceAll("%20"," ");
return truepath[0]+filename;
}//This method will work on Windows and Linux as well.
//You can alternatively use the following line to get the path of your jar file
//classname.class.getProtectionDomain().getCodeSource().getLocation().getPath();
Suppose your jar file is in D:\Test\dist
Then path() will return /D:/Test/dist/myfolder/filename
Now you can place 'myfolder' inside the folder where your jar file is residing
OR
If you want to access some read-only file inside your jar you should copy it to one
of your packages and can access it as
yourClassname.getResource("/packagename/filename.txt");
Related
I am implementing a Branch Predictor for one of my classes and I am trying to read files from my src folder in Eclipse but for some reason it is not able to open the files. I have done this before with the exact same process so I'm not sure what is different.
traceFile is set from the command line and if I print "input", it will print out the correct file path and I have confirmed it is there manually.
ClassLoader loader = BiModalPredictor.class.getClassLoader();
File input = new File(loader.getResource(traceFile).getFile());
Scanner fin = new Scanner(input);
Is there any insight as to why this might be happening? I've tried restarting Eclipse, refreshing the files, and I've also tested it on another program which worked. No idea why it can't find this file.
Resources on the classpath, i.e. available through the classloaders getResource method, will not be files on the file system when your application is deployed as a jar file, or deployed in general. Do not use File with such resources, instead use getResourceAsStream to access the resource content.
Besides, your code is wrong. getResource() returns a URL. If you want a File object from a URL, you should use new File(uri), where the URI is obtained by calling url.toURI().
File input = new File(loader.getResource(traceFile).toURI());
i have a small application which checks for values from a file and display the result in a jframe.
A file contain list of word to check. this file is placed in project folder "testing" and the main source testing.java file is present in location "testing\src\testing"
input file : c:\document..\netbeans\testing\
java file : c:\document..\netbeans\testing\src\testing\
when i place the input file inside folder "c:\document..\netbeans\testing\src\testing\
" the input file is not taken as input, it works only when kept on folder "c:\document..\netbeans\testing\"
so when a jar file is created it has not included the input file in that, even i manually input that is not taking the input file in and working.
some path setting issue? what can be done to solve this issue?
any help pls??
Once you create the jar, the file becomes an embedded resource. If you try to read it as a File it will no long be the same file system path as you originally use in the program. It must now be read from the class path.
To read the file from the class path, you will want to use getClass().getResourceAsStream(), which return an InputStream. If your file is in the same location (package) as your class file, then you should use
InputStream is = getClass().getResourceAsStream("input.txt");
Then you can read from the InputStream
BufferedReader reader = new BufferedReader (new InputStreamReader(is));
This generally happens, when you don't use absolute path...!
As when you run your program from IDE(Netbeans) then the HOME_FOLDER is your ProjectFolder. Relative to which you would have given the file_path(that has to be accessed in your program).
But after building, jar is present in ProjectFolder/dist. When you run the jar file the HomeFolder is not ProjectFolder rather it is ProjectFolder/dist.
So, to make it successful, to need to copy all files and folders from ProjectFolder/dist to ProjectFolder.
Then run the jar.. Hope it will fix the issue
Try putting double backslashes in your file paths. Like this:
c:\\document..\\netbeans\\testing\\src\\testing\\
This is the format that java normally requires it to be in
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).
Suppose I have a Java class that needs to access a file with absolute path
/home/gem/projects/bar/resources/test.csv:
package com.example
class Foo {
String filePath = ????? // path to test.csv
String lines = FileInputStream(new File(filePath).readAllLines();
}
Where the path to Foo.java is /home/gem/projects/bar/src/com/example.
Of course I cannot specify absolute path to the resource file. This is because jar file will be distributed as library for any clients to use in their own environments.
Assume the resource file like test.csv is always in the same path relative to project root. When a jar is created containing Foo.class, this jar also contains test.csv in the same relative path ( relative to project root).
What is the way to specify relative path that would work no matter where the project bar is moved to? Also how can I create a jar file (which can be in any location) so that the path to the resource file test.csv would still be correct.
To keep things simple, I have used invalid Java API ( readAllLines() which reads all the lines and return a string containing entire file content. Also not using try/catch).
Assume csv file can be read as well as written to.
I hope this makes it clear now.
Put the test.csv file into the src folder and use this:
Foo.class.getResourceAsStream("/test.csv")
To get an InputStream for the file. This will work wherever the project is moved, including packaged as a JAR file.
Example:
ProjectX\src\Test.java
ProjectX\resources\config.properties
If you have the above structure and you want to use your config.properties file, this is how you do it:
InputStream input = new FileInputStream("./resources/config.projects");
In this example you don't have to worry about packaging your source into jar file. You can still modify your resources folder anytime.
Use getResource(), as shown here.
I need to read a text file when I start my program. I'm using eclipse and started a new java project. In my project folder I got the "src" folder and the standard "JRE System Library" + staedteliste.txt... I just don't know where to put the text file. I literally tried every folder I could think off....I cannot use a "hard coded" path because the text file needs to be included with my app...
I use the following code to read the file, but I get this error:
Error:java.io.FileNotFoundException:staedteliste.txt(No such file or directory)
public class Test {
ArrayList<String[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
URL url = Test.class.getClassLoader().getResource("src/mjb/staedteliste.txt");
System.out.println(url.getPath()); // I get a nullpointerexception here!
loadList();
}
public static void loadList() {
BufferedReader reader;
String zeile = null;
try {
reader = new BufferedReader(new FileReader("src/mjb/staedteliste.txt"));
zeile = reader.readLine();
ArrayList<String[]> values = new ArrayList<String[]>();
while (zeile != null) {
values.add(zeile.split(";"));
zeile = reader.readLine();
}
System.out.println(values.size());
System.out.println(zeile);
} catch (IOException e) {
System.err.println("Error :"+e);
}
}
}
Ask first yourself: Is your file an internal component of your application?
(That usually implies that it's packed inside your JAR, or WAR if it is a web-app; typically, it's some configuration file or static resource, read-only).
If the answer is yes, you don't want to specify an absolute path for the file. But you neither want to access it with a relative path (as your example), because Java assumes that path is relative to the "current directory". Usually the preferred way for this scenario is to load it relatively from the classpath.
Java provides you the classLoader.getResource() method for doing this. And Eclipse (in the normal setup) assumes src/ is to be in the root of your classpath, so that, after compiling, it copies everything to your output directory ( bin/ ), the java files in compiled form ( .class ), the rest as is.
So, for example, if you place your file in src/Files/myfile.txt, it will be copied at compile time to bin/Files/myfile.txt ; and, at runtime, bin/ will be in (the root of) your classpath. So, by calling getResource("/Files/myfile.txt") (in some of its variants) you will be able to read it.
Edited: Further, if your file is conceptually tied to a java class (eg, some com.example.MyClass has a MyClass.cfg associated configuration file), you can use the getResource() method from the class and use a (resource) relative path: MyClass.getResource("MyClass.cfg"). The file then will be searched in the classpath, but with the class package pre-appended. So that, in this scenario, you'll typically place your MyClass.cfg and MyClass.java files in the same directory.
One path to take is to
Add the file you're working with to the classpath
Use the resource loader to locate the file:
URL url = Test.class.getClassLoader().getResource("myfile.txt");
System.out.println(url.getPath());
...
Open it
Suppose you have a project called "TestProject" on Eclipse and your workspace folder is located at E:/eclipse/workspace. When you build an Eclipse project, your classpath is then e:/eclipse/workspace/TestProject. When you try to read "staedteliste.txt", you're trying to access the file at e:/eclipse/workspace/TestProject/staedteliste.txt.
If you want to have a separate folder for your project, then create the Files folder under TestProject and then access the file with (the relative path) /Files/staedteliste.txt. If you put the file under the src folder, then you have to access it using /src/staedteliste.txt. A Files folder inside the src folder would be /src/Files/staedteliste.txt
Instead of using the the relative path you can use the absolute one by adding e:/eclipse/workspace/ at the beginning, but using the relative path is better because you can move the project without worrying about refactoring as long as the project folder structure is the same.
Just create a folder Files under src and put your file there.
This will look like src/Files/myFile.txt
Note:
In your code you need to specify like this Files/myFile.txt
e.g.
getResource("Files/myFile.txt");
So when you build your project and run the .jar file this should be able to work.
Depending on your Java class package name, you're probably 4 or 5 levels down the directory structure.
If your Java class package is, for example, com.stackoverflow.project, then your class is located at src/com/stackoverflow/project.
You can either move up the directory structure with multiple ../, or you can move the text file to the same package as your class. It would be easier to move the text file.
MJB
Please try this
In eclipse "Right click" on the text file u wanna use,
see and copy the complete path stored in HDD like (if in UNIX "/home/sjaisawal/Space-11.4-template/provisioning/devenv/Test/src/testpath/testfile.txt")
put this complete path and try.
if it works then class-path issue else GOK :)
If this is a simple project, you should be able to drag the txt file right into the project folder. Specifically, the "project folder" would be the highest level folder. I tried to do this (for a homework project that I'm doing) by putting the txt file in the src folder, but that didn't work. But finally I figured out to put it in the project file.
A good tutorial for this is http://www.vogella.com/articles/JavaIO/article.html. I used this as an intro to i/o and it helped.
Take a look at this video
All what you have to do is to select your file (assuming it's same simple form of txt file), then drag it to the project in Eclipse and then drop it there. Choose Copy instead of Link as it's more flexible. That's it - I just tried that.
You should probably take a look at the various flavours of getResource in the ClassLoader class: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html.