Save Java txt file in folder

First of all - I love all of you at Stackoverflow! Everyone is very helpful! Unfortunately, when I go to answer questions, they are too advanced for me: "(

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

{class location} /text/out.txt

Since the program runs on different computers, the location is changing, so I can not put C: // ect

I also know that I need to use the "\\" doubt - but this did not 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 
+4
source share
4 answers

you can use getAbsolutePath () function:

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

and I ask you to take a look at this thread

+5
source

Creating a folder named text in the code directory depends on the file system. To create a file in {project folder}/text/out.txt , you can try the following:

 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(); } 

Remember to catch an IOException !

0
source

The easiest way to make it save your .txt to the root directory of your folder:

 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 want, it will save everything you encoded to write it to the .txt document in the root of your project folder.

Then you can run the application on any computer, and it will still save the document for viewing on any computer.

0
source

You must create directories first and then files. Remember to check their existence first:

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

You do not need to create a File object if the resource already exists.

File.separator is the answer to your slash problems.

-one
source

Source: https://habr.com/ru/post/1393665/


All Articles