Creating a new file, how to specify a directory using a method?

I know how to write file to the specified directory by doing the following:

  public void writefile(){ try{ Writer output = null; File file = new File("C:\\results\\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"); } 

But how can I specify a directory if the directory is specified in the method? For example, a method called getCacheDirectory() . Assuming all necessary imports, etc. Were made..

Thanks:).

+4
source share
1 answer

You mean just

  File file = new File(getCacheDirectory() + "\\results.txt"); 

This would be correct if getCacheDirectory() returned the path as String ; if he returned File , then there is another constructor for this:

  File file = new File(getCacheDirectory(), "results.txt"); 
+8
source

All Articles