由一道题引出的一些东西(求助文章!)
题目: 用io对进行文件简单的加密解密 思路一: 用字节流读取出来存入byte数组,然后创建String对象,再追加到StringBuilder对象上. 然后一直循环追加,最后再将StringBuilder对象转为String对象,再转回byte数组,最后存入文件中. 代码演示: //加密代码
public static void main(String[] args) throws IOException {
byStringBuilder();
}
public static void byStringBuilder() throws IOException {
//读取图片
BufferedInputStream inBuffer =
new BufferedInputStream(new FileInputStream("src/lab/second/page_643/in.jpg"), 1024);
//存读取的字节
byte[] storageArr = new byte[1024];
//用StringBuilder将byte数组先拼接,然后转回为byte数组
StringBuilder builder = new StringBuilder();
int read;
while ((read = inBuffer.read(storageArr, 0, storageArr.length)) != -1) {
//先根据byte数组创建String对象,然后追加到StringBuilder对象上
builder.append(new String(storageArr, 0, read));
}
inBuffer.close();
//重新转化为byte
byte[] bytes = new String(builder).getBytes();
//加密方式为byte数组每个元素加5
for (int i = 0; i
String path = "src/lab/second/page_643/out.jpg";
//读取加密的文件
BufferedInputStream inBuffer =
new BufferedInputStream(new FileInputStream(path));
BufferedInputStream buffer = new BufferedInputStream(inBuffer, 1024);
//用byte数组存读取的字节
byte[] storage = new byte[1024];
int read;
//读出来的字节,用StringBuilder拼接
StringBuilder builder = new StringBuilder();
while ((read = buffer.read(storage, 0, storage.length)) != -1) {
//追加到builder对象上
builder.append(new String(storage, 0, read));
}
//转为byte数组
byte[] bytes = builder.toString().getBytes();
//解密
for (int i = 0; i
//读取图片
BufferedInputStream inBuffer = new BufferedInputStream(
new FileInputStream("src/lab/second/page_643/in.jpg"), 1024);
//存读取的字节的byte数组
byte[] storageArr = new byte[1024];
//存若干个byte数组(因为图片大小肯定大于1kb,所以用若干数组存)
ArrayList list = new ArrayList();
int read;
while ((read = inBuffer.read(storageArr, 0, storageArr.length)) != -1) {
//拷贝数组
byte[] clone = Arrays.copyOfRange(storageArr, 0, read);
//拷贝后添加到list中
list.add(clone);
}
inBuffer.close();
//所有元素值加5
for (byte[] bytes : list) {
addFive(bytes);
}
//存入out.jpg文件中
BufferedOutputStream outStream = new BufferedOutputStream(
new FileOutputStream("src/lab/second/page_643/out.jpg"), 1024);
for (byte[] bytes : list) {
outStream.write(bytes);
}
outStream.close();
}
//给byte数组,每个元素的值加5
public static void addFive(byte[] arr) {
for (int i = 0; i
//读取图片
BufferedInputStream inBuffer =
new BufferedInputStream(new FileInputStream("src/lab/second/page_643/out.jpg"), 1024);
//存读取的字节
byte[] storageArr = new byte[1024];
//存复制的byte数组
ArrayList list = new ArrayList();
int read;
while ((read = inBuffer.read(storageArr, 0, 1024)) != -1) {
//将byte数组克隆,并将其加到list中
byte[] clone = Arrays.copyOfRange(storageArr, 0, read);
list.add(clone);
}
for (byte[] bytes : list) {
divide(bytes);
}
//没开追加模式,直接将原来加密文件覆盖
BufferedOutputStream outBuffer = new BufferedOutputStream(
new FileOutputStream("src/lab/second/page_643/out.jpg"), 1024);
for (byte[] bytes : list) {
outBuffer.write(bytes);
}
outBuffer.close();
}
//给byte数组,每个元素值减5
public static void divide(byte[] arr) {
for (int i = 0; i
for (int i = 0; i |