package com.sandu.ximon.admin.utils;
|
|
import java.io.*;
|
|
/**
|
* @program: machine-fast
|
* @description: 文件操作类
|
* @author: YSS
|
* @create: 2019-04-24 13:58
|
**/
|
public class FileUtil {
|
|
/**
|
* 字段写入文件
|
* @param newStr 字段
|
* @param filePath 文件路径
|
* @return
|
* @throws
|
*/
|
public boolean writeToFile(String newStr,String filePath) throws IOException {
|
|
OutputStream outputStream = null;
|
OutputStreamWriter outputStreamWriter = null;
|
BufferedWriter bufferedWriter = null;
|
|
try{
|
outputStream = new FileOutputStream(new File(filePath));
|
outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8");
|
bufferedWriter = new BufferedWriter(outputStreamWriter);
|
bufferedWriter.write(newStr);
|
bufferedWriter.flush();
|
}catch (Exception e){
|
return false;
|
}finally {
|
try{
|
if(bufferedWriter != null){
|
bufferedWriter.close();
|
}
|
if(outputStreamWriter != null){
|
outputStreamWriter.close();
|
}
|
if(outputStream != null){
|
outputStream.close();
|
}
|
return true;
|
}catch (IOException e){
|
return false;
|
}
|
}
|
}
|
|
public byte[] fileToByte(String filePath){
|
byte[] buffer = null;
|
File file = new File(filePath);
|
FileInputStream fileInputStream = null;
|
ByteArrayOutputStream byteArrayOutputStream = null;
|
|
|
try {
|
fileInputStream = new FileInputStream(file);
|
byteArrayOutputStream = new ByteArrayOutputStream();
|
|
byte[] b = new byte[1024];
|
|
int n;
|
while ((n = fileInputStream.read(b)) != -1){
|
byteArrayOutputStream.write(b, 0, n);
|
}
|
buffer = byteArrayOutputStream.toByteArray();
|
} catch (FileNotFoundException e) {
|
e.printStackTrace();
|
} catch (IOException e) {
|
e.printStackTrace();
|
} finally {
|
try {
|
if(byteArrayOutputStream != null){
|
byteArrayOutputStream.close();
|
}
|
if(fileInputStream != null){
|
fileInputStream.close();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
return buffer;
|
}
|
}
|