Base64相关资料

相关网站 : http://www.cnblogs.com/mofish/archive/2010/11/26/1889126.html

public class AddSec {

public static void main(String[] args){

String addSecStr = getAddSecFileStr("E:\\lml\\原文件.txt"); // 获得加密后字符串
getFile(addSecStr, "E:\\lml\\加密后的文件.txt"); //加密后文件

String fileStr=getFileStr("E:\\lml\\加密后的文件.txt");
releaseFile(fileStr, "E:\\lml\\还原文件.txt"); //解密后的文件
}

/**
* 将文件转化为字节数组字符串,并对其进行Base64编码处理
*
* @param imgFilePath
*            文件路径
* @return
*/
public static String getAddSecFileStr(String imgFilePath) {
byte[] data = null;

// 读取文件字节数组
try {
InputStream in = new FileInputStream(imgFilePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}

byte[] bytes = UrlBase64.encode(data);
return new String(bytes);
}

/**
* 将文件转化为字节数组字符串
*
* @param imgFilePath
*            文件路径
* @return
*/
public static String getFileStr(String imgFilePath) {
byte[] data = null;

// 读取字节数组
try {
InputStream in = new FileInputStream(imgFilePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}

return new String(data);
}

/**
* 对字节数组字符串进行Base64解码并生成文件
*
* @param imgStr
*            加密的字符串
* @param imgFilePath
*            解密后的文件路径
* @return
*/
public static boolean releaseFile(String imgStr, String imgFilePath) {
if (imgStr == null) // 文件数据为空
return false;

try {
// Base64解码
byte[] bytes = UrlBase64.decode(imgStr.getBytes());

for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}

OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}

/**
* 根据字节数组字符串生成文件
*
* @param imgStr
*            加密后的文件字符串
* @param imgFilePath
*            加密后的文件路径
* @return
*/
public static boolean getFile(String imgStr, String imgFilePath) {
if (imgStr == null) // 文件数据为空
return false;

try {
byte[] bytes = imgStr.getBytes();

for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成文件
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}

}

猜你喜欢

转载自l540151663.iteye.com/blog/1932258