java 文件流方法:MultipartFile 转 File,File 转byte[]数组,File转String, String 转File

 java  文件流方法:MultipartFile 转 File,File 转byte[]数组,File转String, String 转File

================================MultipartFile 转 File======================================

/**
* MultipartFile 转 File
*
* @param file
* @throws Exception
*/
public static java.io.File multipartFileToFile(MultipartFile file) {
java.io.File toFile = null;
InputStream ins = null;
try {
if (file == null || file.getSize() <= 0) {
file = null;
} else {

ins = file.getInputStream();
toFile = new java.io.File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);

}
} catch (Exception ex) {
log.error("ERROR:" + ex);
} finally {
// TODO update
IOUtils.closeQuietly(ins);
}
return toFile;
}
================================将文件转换成byte数组======================================

/**
* 将文件转换成byte数组
* @param file
* @return
*/
public static byte[] File2byte(File file) {
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
=================================File文件转String======================================
/**
* File文件转String
*
* @param file
* @return
* @throws IOException
*/
public String fileToString(java.io.File file) throws IOException {
if (file.exists()) {
byte[] data = new byte[(int) file.length()];
boolean result;
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
int len = inputStream.read(data);
result = len == data.length;
} finally {
if (inputStream != null) {
inputStream.close();
}
}
if (result) {
return new String(data);
}
}
return null;
}

=================================字符串输出为文件的方法======================================
/**
* 字符串输出为文件的方法
*
* @param fileContent 文件的字符串
* @param absolutePath 输出路径
* @return
*/
public boolean stringToFile(String fileContent, String absolutePath) {
log.info("stringToFile:start");
boolean result = false;
java.io.File absolutePathFielName = new java.io.File(absolutePath);
OutputStream os = null;
try {
if (absolutePathFielName.exists()) {
absolutePathFielName.delete();
}
os = new FileOutputStream(absolutePathFielName);
os.write(fileContent.getBytes());
os.flush();
result = true;

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
log.info("stringToFile:end");
return result;
}
posted @ 2022-05-18 17:45  Kevin_Zhou_9  阅读(4771)  评论(0编辑  收藏  举报