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();
}
}
java-File转String,String转File
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 原文地址:https://blog.csdn.net/csdn_terence/article/details/7...
- import java.io.UnsupportedEncodingException;import java.m...