package org.jeecg.modules.dnc.utils.file;
|
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.util.ResourceUtils;
|
|
import java.io.*;
|
|
/**
|
* @author clown
|
* * @date 2023/12/29
|
*/
|
@Slf4j
|
public class FileNumUtil {
|
/**
|
* 获取数据内容
|
* @param path
|
* @return
|
*/
|
public static String readFileSum(String path){
|
BufferedReader br = null;
|
try{
|
File file = ResourceUtils.getFile(path);
|
if (!file.getParentFile().exists()){
|
//文件夹不存在 生成
|
file.getParentFile().mkdirs();
|
}
|
InputStreamReader reader = new InputStreamReader(new FileInputStream(file),"UTF-8");
|
br = new BufferedReader(reader);
|
return br.readLine();
|
}catch (Exception e){
|
log.error("数据解析失败,{}", e);
|
return null;
|
}finally {
|
if(br != null){
|
try {
|
br.close();
|
} catch (IOException e) {
|
}
|
}
|
}
|
|
}
|
|
public static boolean updateFile(String newText,String filePath){
|
try {
|
File file = new File(filePath);
|
FileInputStream fis = new FileInputStream(file);
|
byte[] data = new byte[(int) file.length()];
|
fis.read(data);
|
fis.close();
|
|
String content = new String(data, "UTF-8");
|
content = content.replaceAll("Old content", newText); // 替换旧内容为新内容
|
|
FileOutputStream fos = new FileOutputStream(file);
|
fos.write(content.getBytes("UTF-8"));
|
fos.close();
|
} catch (IOException e) {
|
System.out.println("Error occurred: " + e.getMessage());
|
}
|
return true;
|
}
|
|
/**
|
* 方法一:使用 FileWriter 写文件
|
* @param filePath 文件目录
|
* @param content 待写入内容
|
* @throws IOException
|
*/
|
public static void fileWriterSql( String content, String filePath) throws IOException {
|
OutputStreamWriter outputStreamWriter = null;
|
try {
|
File file = new File(filePath);
|
if (!file.exists()){
|
file.createNewFile();
|
}
|
FileOutputStream outputStream = new FileOutputStream(file);
|
if (outputStream != null){
|
outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8");
|
outputStreamWriter.write(content);
|
outputStreamWriter.flush();
|
}
|
}
|
catch (IOException e) {
|
e.getMessage();
|
}
|
finally {
|
try {
|
if (outputStreamWriter != null){
|
outputStreamWriter.close();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
}
|