JAVA文件复制和文件加密存储
生活随笔
收集整理的這篇文章主要介紹了
JAVA文件复制和文件加密存储
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言
提示:本篇文章主要講解一下Java如何復(fù)制文件,以及Java如何加密文件
1.文件復(fù)制
直接給出實(shí)例代碼
代碼如下(示例):
package file;import java.io.*;public class Copy {static boolean fileCopy(String src,String dest) {BufferedInputStream br=null;//創(chuàng)建緩沖流BufferedOutputStream bw=null;//創(chuàng)建緩沖流try {br=new BufferedInputStream(new FileInputStream(src));bw=new BufferedOutputStream(new FileOutputStream(dest));byte[] bytes=new byte[1024];//字節(jié)緩沖區(qū)int m=0;while((m=br.read(bytes))!=-1) {bw.write(bytes,0,m);}//讀取源文件并寫入目標(biāo)文件bw.flush();//刷新輸出流System.out.println("復(fù)制成功");return true;} catch (FileNotFoundException e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();return false;} catch (IOException e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();return false;}finally {try {br.close();} catch (IOException e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();}//關(guān)閉輸入流try {bw.close();} catch (IOException e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();}//關(guān)閉輸出流}}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.文件加密儲(chǔ)存
文件加密儲(chǔ)存只需要對(duì)上面的文件復(fù)制動(dòng)一些手腳
只需要在寫入時(shí)對(duì)數(shù)組進(jìn)行一些操作,下面采用字節(jié)取反的方式
代碼如下(示例):
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++;}//字節(jié)反轉(zhuǎn)進(jìn)行加密或者解密fos.write(enbytes);}fos.flush();System.out.print("轉(zhuǎn)換成功");} catch (FileNotFoundException e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();} catch (IOException e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();}finally {try {fis.close();} catch (IOException e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();}try {fos.close();} catch (IOException e) {// TODO 自動(dòng)生成的 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);}}該程序不但可以加密文件,還可以對(duì)加密的文件解密。
總結(jié)
提示:這里對(duì)文章進(jìn)行總結(jié):
例如:以上就是今天要講的內(nèi)容,本文僅僅簡單介紹了java文件復(fù)制,還講解了文件加密。
總結(jié)
以上是生活随笔為你收集整理的JAVA文件复制和文件加密存储的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 市场部营销经理竞聘演讲稿范文
- 下一篇: 百度地图下载、拼接与坐标改正思路与实例