Writing to a temporary file in java

I want to write to a temporary file in add mode. I see that the file is created, but the data from Stringbuffer is not written to it. Can someone tell me why? Below you will find the code I wrote,

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(); } 
+6
source share
5 answers
 FileWriter fileWriter = new FileWriter(filename.getName(), true); 

it should be

 FileWriter fileWriter = new FileWriter(filename, true); 
+5
source

It works:

 public static void writeToFile(String pFilename, StringBuffer sb) throws IOException { File tempDir = new File(System.getProperty("java.io.tmpdir")); File tempFile = File.createTempFile(pFilename, ".tmp", tempDir); FileWriter fileWriter = new FileWriter(tempFile, true); System.out.println(tempFile.getAbsolutePath()); BufferedWriter bw = new BufferedWriter(fileWriter); bw.write(sb.toString()); bw.close(); } 

Note the use of FileWriter(File, boolean) and System.out.println(tempFile.getAbsolutePath()) .

+4
source

Instead of creating a file in the temp directory, create a file in your working directory and use objFile.deleteOnExit() . It will also work just like creating a file in temp dir.

+1
source

Try calling bw.flush() before closing the entry. Although I think that the author should automatically call a flash before closing ...

0
source
 FileWriter fileWriter = new FileWriter(filename.getName(), true); 

it should be

 FileWriter fileWriter = new FileWriter(filename, true); 

you can also use this

 FileWriter fileWriter = new FileWriter(filename.getAbsolutePath+filename.getName(), true); 

note

 `filename.getName();` 

returns the file name without an absolute path. Thus, it may be that he creates a file in the current working directory and writes to it.

0
source

All Articles