path of a .txt file in java - java

I work with NetBeans IDE an I have a .txt file saved in src/myapp folder. If I run from the IDE, this recognise my
File file=new File("src/myapp/mytext.txt");
But if I build the jar file and double click it or launch it from command line I get this error:
java.io.FileNotFoundException: src\myapp\mytext.txt
I could insert absolute path, but how can I run my jar independently by the position of my project in the computer?

You can obtain the file path indepently of its position with the following:
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("mytext.txt").toString();

Java is expecting to find the file relative to your working directory. So by hardcoding the file in src/myapp/mytext.txt you are expecting the user of your application to have the
file under the same folder structure.
If you are expecting the file to be at the same level of your jar file, you can just use ./mytext.txt. Do not put your mytext.txt under the src in your project. That is for sources you want to compile and/or bundle inside your jar file. In NetBeans move it outside the /src folder, that way when you run the program from your IDE or when you run it externally from your Jar file you find the file at the same level.
If you want the user to be able to specify the location himself of the file, you can also read the command line arguments (the arguments to your public static void main(String[] args)).

there is no such problem
File file=new File("./src/myapp/mytext.txt");

Related

FileNotFoundException in the same directory [duplicate]

This question already has answers here:
Java, reading a file from current directory?
(8 answers)
FileNotFoundException even when the file is there
(3 answers)
Closed 9 days ago.
I'm not entirely sure if this is a Java issue or an IntelliJ issue, but I had a quick question about my File not being found via a path. My Main class is in the same directory as my input.txt file.
I though I should be able to do File file = new File("./input.txt"), except I get FileNotFoundException. When I do something like File file = new File("src/input.txt"), it does work.
I get that this may be a solution, but if I try to run this code outside of IntelliJ without a src directory, this will lead to an error where the File can't be found.
Is there any reason why I can't just do ./input.txt to specify that the File is in the same directory as the Main file?
That's because in IDEA, the working directory of your program is the root directory of your project, not src by default. Therefore, you can access the file by ./src/input.txt or src/input.txt, not input.txt. By the way, it's bad practice to put your resources in src, because it gets mixed with your source code, and it won't be included in the JAR file, which means you cannot access it when your project is packaged as a JAR file. If you are using maven, you can put input.txt inside the resources folder(src/main/resources), and access it by Main.class.getResource("/input.txt")(gives you a URL) or Main.class.getResourceAsStream("/input.txt")(gives you a InputStream) depending on your needs. So that the resources will always be available, no matter you are running the program in IDEA or from a JAR.
FileNotFoundException occurs when the file doesn't exist at the specified location.
File file = new File("./input.txt"), the current working directory (.) is being used as the file location.
If you are running the code from an IDE, the current working directory is usually the project root directory, not the directory where the code file is located.
So, if the input.txt file is located in the same directory as your code file, then you should use the relative path to it.
File file = new File("src/input.txt"), you are specifying the absolute path to the input.txt file, which is inside the src directory.
This is why it works, as the file is guaranteed to exist at that location.
If the file is located in the same directory as your code file, you can use a relative path, and if it's in a different directory, you should use an absolute path to it.

Classloader().getReccourse dont returns the source location in exported jar file

getClass().getResource works fine in Eclipse and returns the path for a file I want to have access to, but after exporting the JAR file my files don't load anymore.
I already tried to print out my path; in Eclipse the console shows:
/C:/Users/.../eclipse-workspace/GameJumpAndRun/bin/file/save1
...but if i run the JAR file by using cmd the message is
file/save1, and no files have been loaded.
System.out.println(getClass().getResource("/file/save"+i).getFile());
file = new File(getClass().getResource("/file/save"+i).getFile());
I need the file as a File and not as a BufferedReader; is there a way to get the same file in both Eclipse and the exported JAR?

Java - Saving file from JAR to disk

I'm trying to save a YAML formatted file packaged in the JAR to the user's disk.
The file is named config.yml and sits directly under one of the project's source folders. I can confirm that the file is packaged in the JAR with WinRAR.
I am using the following code to get the file from the JAR:
File file = new File(this.getClassLoader().getResource("config.yml").getPath());
And I am using this code to copy the file to a directory:
FileUtils.copyFileToDirectory(file, this.getDataFolder());
The getDataFolder() method is implemented by a reliable 3rd party API.
However, when I use a file instance defined with the same getDataFolder() File instance and the path "config.yml":
new File(this.getDataFolder(), "config.yml")
The console logs a FileNotFoundException.
The file path given in the stack trace is this: "file:\C:\Users\Evan\Desk
top\Test%20Server\plugins\lottocrates-1.0.jar!\config.yml" which seems correct. I tried opening the file with run prompt, which I was able to open the JAR with, but not the config.yml file.

Where does Java put resource files when I JAR my program?

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");

Java path to support both IDE and generated JAR

I have an issue with path names in my code. Let's say I have a main class:
com.test.LoadFile.java
Similarly I have a myxml.xml file under com.test. Meaning that the Java file and XML file are under same package.
Can somebody suggest how, when I do (inside LoadFile)
File file = new File("???/myxml.xml")
What should the path be, to support both:
Eclipse IDE code (after including the above code into a single Java project)
and
Run the main LoadFile class outside of the IDE (in a JAR file)
What should I use as the value of the path variable to include in the generated project JAR?
You can read the XML file using getResourceAsStream(), as long as it's in the CLASSPATH:
InputStream is = LoadFile.class.getClassLoader().getResourceAsStream("/myxml.xml");
EDIT: If you are packaging into a .jar, you must specify the complete path of the resource from the jar's root folder using "/" at the beginning of string

Categories

Resources