Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Java txt file to folder

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
like image 521
Rabiani Avatar asked Jan 29 '12 23:01

Rabiani


People also ask

How do I save a file in a directory in Java?

Try something like this: File file = new File("/some/absolute/path/myfile. ext"); OutputStream out = new FileOutputStream(file); // Write your data out. close();

How do you create a text file in a directory in Java?

File file = new File(dir, hash + ". txt"); The key here is the File(File parent, String child) constructor. It creates a file with the specified name under the provided parent directory (provided that directory exists, of course).


1 Answers

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

like image 164
savionok Avatar answered Sep 24 '22 03:09

savionok