Generate a file next to the jar file containing the code - java

I have a jar with my application that should create a file next to it. So in folder I will have this :
Source
|_ MyApplication.jar
|_ generatedFile.txt
Easy thing I thought... nope.. I am lost... I have a code like this:
URL location = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getFile().substring(0, location.getFile().lastIndexOf("/MyContext"));
File file = new File(fileName + ".txt");
File file1 = new File(path + "/MyFileName.txt");
File file2 = new File(path.substring(1) + "/MyFileName.txt");
I tried different combinations, googled alot and I am lost... if I get for example
file1.getPath();
file2.getAbsolutePath();
and so on, the paths are correct... but the file isn't generated... Only working case is the first one, but that is located inside the jar and I don't want that.
I also tried to moving the existing file outside using
Paths.move(...
but that hasn't helped me at all..
Can someone help me with this ? And explain to me why isn't the examples above working ? Thanks..

The call File file = new File("my path string"); just creates a Java File Object instance in memory. You need to write something to the actual file you are targeting. The simplest way to create an empty file is to call file.createNewFile().

Related

How to write relative file path for a file in java project folder

The project name is 'producer'. I have a file located in project folder C:/Users/Documents/producer/krb5.conf.
If I want to write its relative path, should I write
File file = new File("krb5.conf");
or
File file = new File("producer/krb5.conf");
or
File file = new File("./krb5.conf");
?
You can use both your 1. and 3. option.
The 2. option would refer to C:/Users/Documents/producer/producer/krb5.conf.
For the purpose of testing you could try to get the absolute path from each file and print it.
// 1.
File file1 = new File("krb5.conf");
File file2 = new File("producer/krb5.conf");
File file3 = new File("./krb5.conf");
System.out.println(file1.getAbsolutePath());
// Output: C:\Users\Documents\producer\krb5.conf
System.out.println(file2.getAbsolutePath());
// Output: C:\Users\Documents\producer\producer\krb5.conf
System.out.println(file3.getAbsolutePath());
// Output: C:\Users\Documents\producer\.\krb5.conf
The 3. path may look a bit weird at first, but it also works.
C:\Users\Documents\producer\. points to the current directory, so it is essentially the same as C:\Users\Documents\producer.

How to set file path to src folder of project

I want to make a program that you can email to someone and they can run it.
Right now my code for making a file is like this:
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml);
f.createNewFile();
But what if someones username is not S0urceC0ded, or they put the project in a different place? How could I set the file path to the src folder plus the filename?
Leave the path off entirely, it will use the directory of the project.
Change
File f = new File("/Users/S0urceC0ded/Desktop/Code/project/JavaStuffs/src/axmlfile.xml");
To
File f = new File("axmlfile.xml");
I generally use code like this for temporary file storage, this way it gets cleaned up when the application finishes. If required you can allow the user to save a version of the file or move it to a permanent location.
try{
//create a temporary file
File temp = File.createTempFile("axmlfile", ".xml");
System.out.println("Location: " + temp.getAbsolutePath());
}catch(IOException e){
e.printStackTrace();
}

Creating Multiple File Directories

I have a program that takes a file that points to a folder somewhere. I need to then make two separate directories. For example, say I have a file base that points to folder Base. I would then want to create two directories dir1 and dir2.
I know that you do the following:
//Called in constructor
File base = new File (baseFileLocString);
//Make directories
File dir1 = new File (base.getAbsoluteFilePate() + "/dir1");
dir1.mkdir();
File dir2 = new File (base.getAbsoluteFilePate() + "/dir2");
dir2.mkdir();
I do not like this way though. Ideally I could use base and make the directories without having to create new Files. I feel like there should be a more efficient way to do this. Is that the case or no?
There is an alternative
Files.createDirectory(Paths.get(base.getAbsoluteFilePath(), "dir1"));
besides it is better than File.mkdir because if something goes wrong mkdir returns false without expalnation and createDirectory throws an exception which explains what happened
Instead of
File dir1 = new File (base.getAbsoluteFilePath() + "/dir1");
You could use
File dir1 = new File (base, "dir1");
Looks better, but the performance will stay the same

Reading .txt file from another directory

The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file

Netbeans: Try to load file but not found (Java)

I have every time the same problem when I'm trying to load files with Java in Netbeans (6.9).
It seems that the files aren't found. I get the error:
java.lang.NullPointerException
In this context:
File file = new File(this.getClass().getClassLoader().getResource("file.xml").getFile());
// or this also don't work
File file = new File("file.xml");
The file file.xml is in the same directory as the Main.java file.
How could I load this file?
This should work (it does for me):
String path = URLDecoder.decode(getClass().getResource("file.xml").getFile(), "UTF-8");
File f = new File(path);
If I understand the Javadocs correctly, this should be the same as using getClass().getClassloader().getResource() but in my experience it is different
I would suggest that you add a line so it says something along the lines (untested):
File f = new File(....);
System.out.println("f=" + f.getAbsolutePath());
// do stuff with f
This will tell you exactly where the file is expected to be and allow you to figure out what exactly is going on.
Sometimes you might need to add an extra / in front
File file = new File(this.getClass().getClassLoader().getResource("/file.xml").getFile());

Categories

Resources