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(); } } 
1
  • already did that but it didn't work... Commented Oct 8, 2014 at 7:19

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

ok i'll try it, does this work both on WINDOWS and LINUX?
Yep it's valid for both...
hmm it returns a blank
Returns a blank what?
sorry miscode but I did it and it still creates file in root
|
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("/")); 

3 Comments

directory? what is that is that a variable sir? sorry, still not getting used to all these
File directory = new File ("."); The file which you create
see my edit u can find the absolute path in string (both in windows and linux)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.