file Encryption / decryption example.
Package io;
Import java.io.*;
public class Encrypt {
private file file; storing file object information
Byte[] BUF; buffer that stores all data in the file randomaccessfile fp;
Constructs a filed object store with the file specified by the parameter filename
Allocating storage space equal to the length of the file for the buffer buf
Public Encrypt (String filename) {
File=new File (filename);
Buf=new byte[(int) file.length ()];
}
Public Encrypt (File destfile) {
File = DestFile;
BUF = new byte[(int) file.length ()];
}
open files in read-write mode
public void OpenFile () throws filenotfoundexception{
Fp=new randomaccessfile (file, "RW");
}
Close File
public void CloseFile () throws ioexception{
Fp.close ();
}
encrypting / decrypting a file
public void Coding () throws ioexception{
reads the contents of the file into the buffer fp.read (BUF);
to reverse the contents of a buffer
for (int i=0;i<buf.length;i++)
Buf[i]= (Byte) (~buf[i]);
position the file pointer to the file header
Fp.seek (0);
writes the contents of the buffer to a file fp.write (BUF);
}
public static void Main (string[] args) {
Encrypt OA;
if (args.length<1) {
System.out.println (" you need to specify the name of the encrypted file!") ");
Return
}
try {
OA = new Encrypt (args[0]);
Oa.openfile ();
Oa.coding ();
Oa.closefile ();
System.out.println (" file encryption succeeded!") ");
} catch (FileNotFoundException e) {
System.out.println (" File not found:" +args[0]);
}catch (IOException e) {
System.out.println (" file read/write error :" +args[0]);
}
}
}
Randomaccessfile class for file encryption