【校招VIP】JAVA文件复制和文件加密存储

05月11日 收藏 0 评论 1 java开发

【校招VIP】JAVA文件复制和文件加密存储

文章声明:转载来源:https://blog.csdn.net/qq_51228515/article/details/120977887

前言
提示:本篇文章主要讲解一下Java如何复制文件,以及Java如何加密文件

1.文件复制
直接给出实例代码
代码如下(示例):

package file;

import java.io.*;



public class Copy {

static boolean fileCopy(String src,String dest) {
BufferedInputStream br=null;//创建缓冲流
BufferedOutputStream bw=null;//创建缓冲流

try {
br=new BufferedInputStream(new FileInputStream(src));
bw=new BufferedOutputStream(new FileOutputStream(dest));

byte[] bytes=new byte[1024];//字节缓冲区
int m=0;
while((m=br.read(bytes))!=-1) {
bw.write(bytes,0,m);
}//读取源文件并写入目标文件
bw.flush();//刷新输出流
System.out.println("复制成功");
return true;
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块

e.printStackTrace();
return false;
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
return false;
}finally {
try {
br.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}//关闭输入流
try {
bw.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}//关闭输出流


}



}
public static void main(String[] args) {
String src="C:\\Users\\asus\\Pictures\\timg1.jpg";
String dest="C:\\Users\\asus\\Pictures\\timg3.jpg";
fileCopy(src,dest);


}









}

2.文件加密储存
文件加密储存只需要对上面的文件复制动一些手脚

只需要在写入时对数组进行一些操作,下面采用字节取反的方式

代码如下(示例):

package file;
import java.io.*;
public class jiami {
static void EncryptionOrDecryPtion(String src,String ensrc) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream(src);
fos=new FileOutputStream(ensrc);

//FileInputStream fis=new FileInputStream(src);
//FileOutputStream fos=new FileOutputStream(ensrc);
byte[] bytes=new byte[512];
int readCount=0;
while((readCount=fis.read(bytes))!=-1) {
int i =0;
byte[] enbytes=new byte[readCount];
System.arraycopy(bytes, 0, enbytes, 0, readCount);
for (byte b:enbytes) {
b=(byte)~b;
enbytes[i]=b;
i++;

}//字节反转进行加密或者解密
fos.write(enbytes);
}
fos.flush();
System.out.print("转换成功");
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String src="C:\\Users\\asus\\Desktop\\ceshi.txt";
String dest="C:\\Users\\asus\\Desktop\\ceshi2.txt";
EncryptionOrDecryPtion(src,dest);

}


}

该程序不但可以加密文件,还可以对加密的文件解密。

C 1条回复 评论
胡俟

写的不错 共勉~,最近也在开始写博客。大佬们来翻牌啊!

发表于 2022-08-29 21:00:00
0 0