Monday, December 28, 2015

How To Make Program to Corrupt File (Java)

Sometime we intentionally want our file to be corrupted e.g. to test software reliability. So, I made a program in Java that intentionally corrupt file. Please be careful to use this program as this program will make your file corrupt and cannot be reverted. Please backup your file before making it corrupt.

OK, the logic is very simple. For each byte in the file, I simply put any random character (ASCII character is from 0 to 255). Here is the complete Java program:

import java.io.RandomAccessFile;
import java.util.Random;

/**
 *
 * @author arwankhoiruddin
 */
public class CorruptFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String FILEPATH = args[0];

        System.out.println("File to corrupt: " + FILEPATH);
        System.out.println("File corruption process started");
     
        try {
            RandomAccessFile file = new RandomAccessFile(FILEPATH, "rw");
            Random r = new Random();
            for (int i=0; i                
                String dt = "" + (char) r.nextInt(255);
                file.seek(i);
                file.write(dt.getBytes());
            }
            file.close();
         
            System.out.println("File " + FILEPATH + " has now been corrupted. Enjoy!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


No comments: