记录一下java读取写入文件的方法,也算是回顾了,太久没看了...
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
public static void main(String[] args) {
//原文件路径+文件名
String filePath = "C:\\Users\\gawei\\Desktop\\hmsd.txt";
//目标文件路径+文件名
String destPath = "C:\\Users\\gawei\\Desktop\\hmsdNew.txt";
//读取文件,并做日期格式转化
List<String> newDate = readTxtFile(filePath);
//写入新格式日期到txt
writeFile(newDate, destPath);
}
//读取文件,并保存为List
public static List<String> readTxtFile(String filePath) {
List<String> newDate = new ArrayList<>();
try {
String encoding = "UTF-8";//编码格式
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
String newdate = handle(lineTxt);
System.out.println(newdate);
newDate.add(newdate);
}
read.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return newDate;
}
//写入文件
private static void writeFile(List<String> newDate, String destPath) {
File file = new File(destPath);
try {
if (!file.exists()) {
file.createNewFile(); //文件若不存在则新建
}
FileWriter fileWriter = null;
fileWriter = new FileWriter(file);
BufferedWriter bw;
bw = new BufferedWriter(fileWriter);
for (int j = 0; j < newDate.size(); j++) {
bw.write(newDate.get(j));
bw.newLine();//换行
bw.flush();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//转化日期从2023/3/20 10:42:00 转化为 2023-03-20 10:42:00
public static String handle(String s) {
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = null;
try {
d1 = df.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return df1.format(d1);
}
}