Save Java txt file to folder

Rabiani picture Rabiani · Jan 30, 2012 · Viewed 20.3k times · Source

First of all - I love you all at Stackoverflow! Everyone is very helpful! Sadly when I go to answer questions they are all too advance for me :'(

I want to save the text file to a folder - but not an absolute folder for example I want to save it to

{class location}/text/out.txt

Because the program is being worked on different computers the location changes, so I can't put C:// ect

I also know I need to use doubt "\\" - but this didn't work in my attempts

public void writeFile (int ID, int n) {
            try{
                    String Number = Integer.toString(n);
                    String CID = Integer.toString(ID);
          FileWriter fstream = new FileWriter("//folder//out.txt",true); //this don't work 
          BufferedWriter out = new BufferedWriter(fstream);
          out.write(Number+"\t"+CID);
          out.newLine();
          out.close();
          }//catch statements etc

Answer

savionok picture savionok · Jan 30, 2012

you can use getAbsolutePath() function:

 FileWriter fstream = new FileWriter(new File(".").getAbsolutePath()+"//folder//out.txt",true);

and i sugest you to take a look at this thread