Question

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
Was it helpful?

Solution

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

OTHER TIPS

Creating a folder named text in the code's directory is file system independent. To create a file in {project folder}/text/out.txt you can try this:

String savePath = System.getProperty("user.dir") + System.getProperty("file.separator") + text;
File saveLocation = new File(savePath);
    if(!saveLocation.exists()){
         saveLocation.mkdir();
         File myFile = new File(savePath, "out.txt");
         PrintWriter textFileWriter = new PrintWriter(new FileWriter(myFile));
         textFileWriter.write("Hello Java");
         textFileWriter.close();
     }

Don't forget to catch the IOException!

The simplest way to make it save your .txt to the root of your folder is to do this:

public class MyClass 
{
public void yourMethod () throws IOException 
{

FileWriter fw = null;

try

{

 fw = new FileWriter ("yourTxtdocumentName.txt");

// whatever you want written into your .txt document

fw.write ("Something");
fw.write ("Something else");
System.out.println("Document completed.");
fw.close

}
catch (IOException e)
{
e.printStackTrace();
}

} // end code
} // end class

Then you call this method whenever you like, it will save whatever you have coded to be written into the .txt document into the root of your project folder.

You can then run your application on any computer, and it will still save the document for viewing on any computer.

You should first create directories and then the files. Remember to firstly check their existence:

new File("some.file").exists();
new File("folder").mkdir(); // creates a directory
new File("folder" + File.separator + "out.txt"); // creates a file

Don't need to create a File object if resource already exist.

File.separator is the answer for your localization problems with slashes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top