Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - how do I write a file to a specified directory

I want to write a file results.txt to a specific directory on my machine (Z:\results to be precise). How do I go about specifying the directory to BufferedWriter/FileWriter?

Currently, it writes the file successfully but to the directory where my source code is located. Thanks

    public void writefile(){      try{         Writer output = null;         File file = new File("results.txt");         output = new BufferedWriter(new FileWriter(file));          for(int i=0; i<100; i++){            //CODE TO FETCH RESULTS AND WRITE FILE         }          output.close();         System.out.println("File has been written");      }catch(Exception e){         System.out.println("Could not create file");     } } 
like image 358
user726219 Avatar asked Apr 26 '11 22:04

user726219


People also ask

How do I save a file in a specific 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 I add files to an existing directory in Java?

Just add the selected path to the file you want to create. If you don't add it will use the current application path, not the one you want. File file = new File(folder, "test.

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 should use the secondary constructor for File to specify the directory in which it is to be symbolically created. This is important because the answers that say to create a file by prepending the directory name to original name, are not as system independent as this method.

Sample code:

String dirName = /* something to pull specified dir from input */;  String fileName = "test.txt"; File dir = new File (dirName); File actualFile = new File (dir, fileName);  /* rest is the same */ 

Hope it helps.

like image 117
Kaushik Shankar Avatar answered Sep 28 '22 17:09

Kaushik Shankar