之前已经研究了文本文件转二进制文件,还记得之前的想法吗。通过在二进制文件中插入一个字节,使文件无法正常打开。
直接贴代码
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
public class s
{ public static byte[] fileToByte(String filepath) throws IOException{
byte[] bytes = null;
FileInputStream fis = null;
try{
File file = new File(filepath);
fis = new FileInputStream(file);
bytes = new byte[(int) file.length()];
fis.read(bytes);
}catch(IOException e){
e.printStackTrace();
throw e;
}finally{
fis.close();
}
return bytes;
}
public static void mywrite(byte[] data,String str){
File file = new File(str); //1、建立连接
OutputStream os = null;
try {
//2、选择输出流,以追加形式(在原有内容上追加) 写出文件 必须为true 否则为覆盖
os = new FileOutputStream(file,false);
// //和上一句功能一样,BufferedInputStream是增强流,加上之后能提高输出效率,建议
// os = new BufferedOutputStream(new FileOutputStream(file,true));
/* String string = "Programmer say : Hello World!";
byte[] data = string.getBytes(); //将字符串转换为字节数组,方便下面写入
*/
os.write(data, 0, data.length); //3、写入文件
os.flush(); //将存储在管道中的数据强制刷新出去
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件没有找到!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("写入文件失败!");
}finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("关闭输出流失败!");
}
}
}
}
public static void main(String args[]) throws IOException{
byte b[]=fileToByte("/storage/sdcard1/hh.bmp");
byte[] b2=new byte[b.length+1];
for(int i=0;i<b.length;i++)
{
b2[i+1]=b[i];
//System.out.println(String.format("%08d",Integer.parseInt(Integer.toBinaryString(0xff & b[i]))));
}
b2[0]=23;
mywrite(b2,"/storage/sdcard1/nor.bmp");
}
}
为了方便我采用了在第一个字节处插入一个字节,实际上可以在其它地方插入
尝试打开nor.bmp发现无法打开,成功了!
解密时只要再将插入的去掉就ok了