0

I've been searching for this and many answers came out but it just wasn't the solution I was looking for so I came here and try to ask help to you guys...

I want to create a .txt file in the same folder where the JAR file is located (dist folder)...

I tried using System.getProperty("user.dir") it works fine when I run it on windows and using netbeans the file created is always in the same folder where the jar file is but when I run it on LINUX it saves the file in root... but the folder where the jar file is on the desktop

it creates in the same folder when I use the terminal to open the jar file

private static String directory=System.getProperty("user.dir");
private final String sample=directory+File.separator+"sample.txt";


public void createFile()
{
     File file=new File(sample);
    try(FileWriter fw=new FileWriter(file))
    {
        fw.write("INSERT ME WHERE MY JAR IS");
        fw.flush();
        fw.close();
    }catch(IOException ex)
    {
        ex.printStackTrace();
    }
}
codename_newbie
  • 3
  • 1
  • 1
  • 5

2 Answers2

10

You can refer to your working directory with

File directory = new File(".")

and you can access a file on it using

System.getProperty(directory.getCanonicalPath() + File.separator + "my.properties")

OR

System.getProperty("." + File.separator + "my.properties")

The "." refers to your current directory. The use of File.separator ensures your get '/' in UNIX-based file systems and "\" in NTFS.

travega
  • 8,284
  • 16
  • 63
  • 91
0

Had same problem: These will work for LINUX

Current directory's canonical path: directory.getCanonicalPath());

Current directory's absolute path: directory.getAbsolutePath());

If it varies in windows try to check for OS and run code: Like

System.getProperty("os.name");

Or else Use:

String absolutePath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf("/"));
George Rosario
  • 761
  • 11
  • 24