How to delete only file contents in java?

Can I find out how can I delete the contents of a file in java? Thanks in advance.

+7
java android
source share
6 answers

How about this:

new RandomAccessFile(fileName).setLength(0); 
+13
source share
 new FileOutputStream(file, false).close(); 
+3
source share

Open the file for recording and save it. It deletes the contents of the file.

+1
source share

You can do this by opening the file for writing and then trimming its contents , the following example uses NIO:

 import static java.nio.file.StandardOpenOption.*; Path file = ...; OutputStream out = null; try { out = new BufferedOutputStream(file.newOutputStream(TRUNCATE_EXISTING)); } catch (IOException x) { System.err.println(x); } finally { if (out != null) { out.flush(); out.close(); } } 

Another way : trim only the last 20 bytes of the file:

 import java.io.RandomAccessFile; RandomAccessFile file = null; try { file = new RandomAccessFile ("filename.ext","rw"); // truncate 20 last bytes of filename.ext file.setLength(file.length()-20); } catch (IOException x) { System.err.println(x); } finally { if (file != null) file.close(); } 
+1
source share

Maybe the problem is that it leaves only the head, I think, not the tail?

 public static void truncateLogFile(String logFile) { FileChannel outChan = null; try { outChan = new FileOutputStream(logFile, true).getChannel(); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("Warning Logfile Not Found: " + logFile); } try { outChan.truncate(50); outChan.close(); } catch (IOException e) { e.printStackTrace(); System.out.println("Warning Logfile IO Exception: " + logFile); } } 
+1
source share
 try { PrintWriter writer = new PrintWriter(file); writer.print(""); writer.flush(); writer.close(); }catch (Exception e) { } 

This code will delete the current contents of the β€œfile” and set the file length to 0.

0
source share

All Articles