I am reading an ascii file in in my eclipse project.
The default output folder is set as
my_proj/classes
It is on my source path and when I build it goes into my classes directory. All ok. However, when I try to get a handle to it in my code by doing
File myFile = new File("myFile.txt")
it won't work because that API looks at my project root. Not at my classes dir.
When I do:
System.out.println("Current path is = " + new File(".").getAbsolutePath ());
The project roo comes back not my classes dir.
So hence I can't get a handle to my File.
I would like to just have the File on the classpath and for the code to pick it up
Any tips?
You can use getClass().getClassLoader().getResource("Your_File")
and then use something like
File file=new File(url.toURI());
Edit: as pointed out by Sotirios Delimanolis and jb-nizet, if "Your_File" is not a file on the file system but is bundled within a jar, in that case you will have to work with the inputstream, getClass().getClassLoader().getResourceAsStream("Your_File")
Related
I want to print the output in a file. I am using PrintWriter IO stream to add the data to file. When I want to check it, I don't know where the file is located. I am using Eclipse IDE.
PrintWriter writer=new PrintWriter("output.txt","UTF-8");
writer.println("Barcode Reader");
So can any one point me to where the file will be located?
I had this problem initially when I switched to using Eclipse. The current relative path is set to the project directory. The following code snippet will explain this better.
Path currentRelativePath = Paths.get("");
String myPath = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + myPath);
Note that the Path object is received from a get method in Paths((plural)). They are located in java.nio.file.
Further information about this can be found in the Path Operations page.
Does that solve your problem?
It will be present in your project's root folder.
Just open your project folder from your workspace using Explorer and it will be there.
With a filename like "output.txt" it will be placed into the current working directory.
Unless you specify otherwise, in Eclipse that will be the root directory of your project.
You may have to click "Refresh" for it to show up in the File Explorer.
If you give you file name directly like C:\java\workspace\ocpjp7 (a Windows
directory) or /home/nblack/docs (the docs directory of user nblack on UNIX), you can find your file in those directories. But if you don't give the full path, it will be in your current working directory.
"output.txt" -> root
"src/resources/output.txt" -> in resources package
At first you should create this file with File in directory you want.Next step to write data into the file. Your file will be located in directory you want , you set when file has created.
Also check this class FileInputStream
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.
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
here is the structure of my project.
proj
---src
----main
----java
----Main.java
----resources
----res.txt
I am using m2eclipse plugin with Eclipse.
In Main.java, I have
File f = new File("res.txt"); System.out.println(f.getAbsolutePath());
When I run mvn exec:java, the path got printed out is "...\proj\res.txt". How can I make it look for the resource file in "...\proj\target\classes" directory?
EDIT:
Thanks for the answers to my original question. I have a follow-up questions:
So basically what I want to do is to have the Main class read the "res.txt" and then generate a new "newres.txt" to the resources directory so that I can package this new "newres.txt" to the jar file in the package phase later. Currently I mounted this exec:java to the prepare-package phase. How should I create this "newres.txt" in the resources directory without a hard-coded absolute path or depending on the directory structure of Maven?
I guess I will answer my own question, Thread.currentThread().getContextClassLoader().getResourceAsStream()
works the best for me, especially when the project produces a jar dependency for another web project.
Figure I'd add to the answers.
You can also use:
InputStream file = ClassLoader.getSystemResourceAsStream("res.txt");
Try
InputStream IS = Main.class.getResourceAsStream("res.txt");
to access the content of res.txt. Pay attention to the encoding of your text file (beware of defaults). If your maven project is set on UTF-8 for example, make sure res.txt is encoded in UTF-8 too, otherwise, you'll get funny errors at runtime.
When run from eclipse, res.txt is created in/reader from the folder where eclipse is started. Hence the output.
If you want to make the code look at the file in a specific folder, which is present in your classpath, then you should try using getResourceAsStream() method.
Alternately you can specify the absolute path of the file.
Here is anther solution:
String str = "target/classes/res.txt";
InputStream is = new FileInputStream(new File(str));
If you exec java in root folder, and you resource will compile to target/classes folder, you can write you code like this.
I was just wondering if there is a way to find out where a java program will be searching for files.
I am trying to load a settings file with FileInputStream fstream = new FileInputStream("ldaplookup.ini"); but it is throwing a File not found error. The ini file is in the same folder as the class file but i am assuming it is searching somewhere else.
Thanks, -Pete
FileInputStream looks up the file relative to the path of execution. If the resource file is in the same folder as the class, you can try using:
InputStream stream = this.getClass().getResourceAsStream("ldaplookup.ini");
Java loads files from the current working directory for a relative path. If you want to see what is, try this:
System.out.println(System.getProperty("user.dir"));
Since "new FileInputStream("ldaplookup.ini");" is equivalent to "new FileInputStream("./ldaplookup.ini");", you could try:
System.out.println(new File(".").getAbsolutePath());
A much more reliable method to read files that are distributed with your classes is to use Class.getResourceAsStream() - it will look in the directory in the classpath where the class you're calling it on is situated, and it will even work when everything is packaged in a JAR file.
Not direct answer but a helpful alternative:
You can use a resource bundle instead.
rename ldaplookup.ini to ldaploopup.properties
And load it with:
ResourceBundle bundle = ResourceBundle.getBundle("ldaplookup");
String s = bundle.getString("url");
ResourceBundle search in the classpath for a .properties file among other strategies.
Etc. etc.
p.s.
To know what is the base path for your program try ( as suggested before: )
System.out.println(new File("."));