首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

(转)java保险删除某个文件

2013-06-25 
(转)java安全删除某个文件import java.io.*import java.nio.*import java.nio.channels.*import java.s

(转)java安全删除某个文件

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.security.SecureRandom;

public class SecureDelete {

   public static void main(String[] args) throws IOException {
   
     File file = new File(args[0]);
     if (file.exists()) {
     SecureRandom random = new SecureRandom();
     RandomAccessFile raf = new RandomAccessFile(file, "rw");
     FileChannel channel = raf.getChannel();
     MappedByteBuffer buffer
       = channel.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
     // overwrite with zeros
     while (buffer.hasRemaining()) {
       buffer.put((byte) 0);
     }
     buffer.force();
     buffer.rewind();
     // overwrite with ones
     while (buffer.hasRemaining()) {
       buffer.put((byte) 0xFF);
     }
     buffer.force();
     buffer.rewind();
     // overwrite with random data; one byte at a time
     byte[] data = new byte[1];
     while (buffer.hasRemaining()) {
       random.nextBytes(data);
       buffer.put(data[0]);
     }
     buffer.force();
     file.delete();
     }
  }
}
//该片段来自于http://www.codesnippet.cn/detail/03122012774.html

  其中用到了NIO,其实就是用混乱的数据重新填充下文件

热点排行