Reads a file to determine the number of bytes it contains and then overwrites all those bytes with 0s - Java File Path IO

Java examples for File Path IO:Binary File

Description

Reads a file to determine the number of bytes it contains and then overwrites all those bytes with 0s

Demo Code

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
  public static void main(String[] arguments) {
    try {//  w  w w  .ja v a 2  s  .  c  o  m
      FileInputStream file = new FileInputStream("junkfile.dat");
      boolean eof = false;
      int size = 0;
      while (!eof) {
        int input = file.read();
        if (input == -1) {
          eof = true;
        } else {
          size++;
        }
      }
      file.close();
      FileOutputStream outFile = new FileOutputStream("junkfile.dat");
      for (int i = 0; i < size; i++) {
        outFile.write((byte) 0);
      }
      outFile.close();
    } catch (IOException e) {
      System.out.println("Error -- " + e.toString());
    }
  }
}

Result


Related Tutorials