Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a temporary file in java

Tags:

People also ask

What is a temporary file in Java?

Creating a temporary fileThe File class in Java provides a method with name createTempFile(). This method accepts two String variables representing the prefix (starting name) and suffix(extension) of the temp file and a File object representing the directory (abstract path) at which you need to create the file.

Where does Java store temp files?

getProperty("java. io. tmpdir"); Commonly, in Windows, the default temporary folder is C:\Temp , %Windows%\Temp , or a temporary directory per user in Local Settings\Temp (this location is usually controlled via the TEMP environment variable).


I want to write to a temporary file in an append mode. I see that the file is created but the data from the Stringbuffer is not getting written to it. Can somebody tell me why? Please find below the code I have written,

public static void writeToFile(String pFilename, StringBuffer sb)
        throws IOException {

    String property = "java.io.tmpdir";


    String tempDir = System.getProperty(property);

    File dir = new File(tempDir);
    File filename = File.createTempFile(pFilename, ".tmp", dir);
    FileWriter fileWriter = new FileWriter(filename.getName(), true);
    System.out.println(filename.getName());
    BufferedWriter bw = new BufferedWriter(fileWriter);
    bw.write(sb.toString());
    bw.close();
}