2

I want to create a new .txt file inside my project folder and I want to give it this path:

Contents/FrameClasses/Data/Datafiles/MYFILE.txt

What I use to make the folder is this:

File MYFILE = new File("Contents/FrameClasses/Data/Datafiles/MYFILE.txt");
MYFILE.getParentFile().mkdir();
try{
    if(MYFILE.createNewFile()){
        //do stuff here
    }
}catch (Exception e){
    //do stuff with the exception...
}

Whenever I do this I get an error saying:

java.io.IOException: No such file or directory

The error is fixed if I add src/ to the beginning of my path and make it like this:

src/Contents/FrameClasses/Data/Datafiles/MYFILE.txt

But the src/ is not part of my project as everything is contained inside the Contents folder I've made. When I build the .jar file it gives the same error if I run it once I add the src/ to the path.

What would be the proper way to create this file ?
PS: I've tried using a shorter path like this one as well: Datafiles/MYFILE.txt without success. Also, the class I use to make the file is contained inside the folder Data alongside with Datafiles as shown in the original path.

Lae
  • 832
  • 1
  • 13
  • 34
  • try fully pathing it from '/' You are currently using a relative path from where you are running the code from. see http://stackoverflow.com/questions/11747833/getting-filesystem-path-of-class-being-executed – Scary Wombat Apr 21 '17 at 02:04
  • @ScaryWombat That way it would work but what I am trying to achieve is to create the text file **inside** the project even once it becomes a `.jar` file. – Lae Apr 21 '17 at 02:06
  • 1
    so the `.jar` file could be anywhere, that is why you need to use a full path – Scary Wombat Apr 21 '17 at 02:09
  • You can't create a file within a jar file at runtime. It'd be outside of it – OneCricketeer Apr 21 '17 at 02:13
  • Why? The project won't be there at runtime. You should be looking to create the file relative to the JAR location, or the user's home directory, or a temp directory, etc. – user207421 Apr 21 '17 at 03:52

1 Answers1

0

Short Answer: You should not write file into in class folder.

In the runtime, we will run Java Program with jar file, and jar essentially is a zip file, you can not write into your own runtime jar like this directly by path. if you run this with a jar file, it maybe will throw exception like:

java.io.IOException: The filename, directory name, or volume label syntax is incorrect

And:

  1. src/Contents/FrameClasses/Data/Datafiles/MYFILE.txt this path work, I think you are running in your IDE or other way, but not run with a released jar file.

  2. File MYFILE = new File(this.getClass().getResource("/").getPath() + "Contents/FrameClasses/Data/Datafiles/MYFILE.txt") should work when you run without a jar.

chengpohi
  • 14,064
  • 1
  • 24
  • 42