package org.spc.system.api.controller.v1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class TxtTest {
//1. 读取文件内容
public static String txt2String(File file){
StringBuilder result = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
result.append(System.lineSeparator()+s);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return result.toString();
}
//2. 循环语句分行
public static List<String> txt2Line(File file){
List<String> lineList = new ArrayList<>();
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
lineList.add(s);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return lineList;
}
//3. 每一行用循环语句分出单个数据
public static List<String> txt2Line(String str){
List<String> list = new ArrayList<>();
String[] as = str.split(",");
for (int i = 0; i < as.length; i++) {
System.out.println(as[i]);
}
return list;
}
//4.每个数据利用华氏转换成摄氏并输出
public static int f2c(String str){
int C;
int F = Integer.parseInt(str);
C = (F - 32)*5/9;
System.out.println(C);
return C;
}
//5. 将最后的字符写入文件中
public static void WriteStringToFile(String filePath,List<String> c) {
try {
StringBuffer str = null;
FileOutputStream fos = new FileOutputStream(filePath);
for(String s:c){
str.append(s+",");
}
fos.write(str.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args){
//获取文件
File file = new File("TxtTest.txt");
//1. 读取文件内容
System.out.println(txt2String(file));
//2. 循环语句分行
List<String> lineList= txt2Line(file);
//3. 每一行用循环语句分出单个数据
List<String> strList=new ArrayList();
for(String str:lineList){
strList.addAll(txt2Line(str));
}
List<String> c=new ArrayList();
//4.每个数据利用华氏转换成摄氏并输出
for(String s:strList){
c.add(f2c(s)+"");
}
//5. 将最后的字符写入文件中
String filePath="newTxtTest.txt";
WriteStringToFile(filePath,c);
}
}