import org.apache.commons.codec.binary.Base64;
import java.io.*;
/**
* @description:
* @author: Mr.FZT
* @create: 2020-06-29
**/
public class FileUtil{
public static void main(String[] args) {
String s =file2String("/Users/wf/Downloads/测试.xlsx");
System.out.println(s);
string2File(s, "/Users/wf/Downloads/测试2.xlsx");
}
private static void string2File(String base64Code, String targetPath) {
byte[] buffer;
FileOutputStream out =null;
try {
Base64 base64 =new Base64();
//解码
buffer = base64.decode(base64Code);
out =new FileOutputStream(targetPath);
out.write(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out !=null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static Stringfile2String(String path) {
File file =new File(path);
FileInputStream fis =null;
StringBuilder content =new StringBuilder();
try {
fis =new FileInputStream(file);
int length =2 *1024 *1024;
byte[] byteAttr =new byte[length];
int byteLength;
while ((byteLength = fis.read(byteAttr, 0, byteAttr.length)) != -1) {
String encode;
if (byteLength != byteAttr.length) {
byte[] temp =new byte[byteLength];
System.arraycopy(byteAttr, 0, temp, 0, byteLength);
Base64 base64 =new Base64();
encode = base64.encodeToString(temp);
content.append(encode);
} else {
Base64 base64 =new Base64();
encode = base64.encodeToString(byteAttr);
content.append(encode);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis !=null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return content.toString();
}
}
网友评论