您的位置:首页 > 其它

通过文件字节流字符串传输文件

2018-01-11 16:08 246 查看
1.将文件解析为字节流字符串
String strFilePathName = "文件全路径";
byte[] data = null ;//data数组为文件解析后得到的数组
try {
FileInputStream in =new FileInputStream(new File(strFilePathName));
//当文件没有结束时,每次读取一个字节显示
data=new byte[in.available()];
in.read(data);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
String str= Base64.encode(data); //获得加密字字符串

注: 需要的jar包 com.sun.org.apache.xml.internal.security.utils.Base64;

2.将字节流字符串转为文件

public void getFile(String str){

String filePath = "文件存储路径";

BufferedOutputStream bos = null;

FileOutputStream fos = null;

File file = null;

byte[] srtbyte = str.getBytes();

byte[] bytes = Base64.decode(srtbyte);//解码字符串

try {

File dir = new File(filePath);
if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath+"\\"+"文件名字");//完整的文件名称(+后缀)

fos = new FileOutputStream(file);

bos = new BufferedOutputStream(fos);

bos.write(bytes);

}catch (Exception e) {
e.printStackTrace();

} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐