Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - creating new file, how do I specify the directory with a method?

I know how to write a file to a specified directory by doing this:

 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 do I go on specifying the directory, if the directory is set in a method? A method called getCacheDirectory() for example. Assuming that all necessary imports etc have been done..

Thanks :).

like image 715
Mike Haye Avatar asked Jan 20 '23 11:01

Mike Haye


1 Answers

You mean just

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

That would be right if getCacheDirectory() returned the path as a String; if it returned a File, then there's a different constructor for that:

    File file = new File(getCacheDirectory(), "results.txt");
like image 153
Ernest Friedman-Hill Avatar answered Jan 31 '23 06:01

Ernest Friedman-Hill