package service;标签:java,读取数据,str,new,import,txt,逐行,String From: https://www.cnblogs.com/zxlk-home/p/17864753.html
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
/**
* 从一个txt文件中读取数据,并且再把读取到的数据修改为想要的格式,再每行写入到另一个txt文件
* 源数据格式:group1/M00/01/05/rBHxPl_IBACAFoQ6AABrWjSdvLk9246245
* 目标数据格式:group1,M00/01/05/rBHxPl_IBACAFoQ6AABrWjSdvLk9246245
*
* @author zhangkuan
* @version Id: WriteFileByLineTest.java, v 0.1 2023/11/29 15:00 PM zhangkuan Exp $$
*/
public class WriteFileByLineTest {
public void test() throws IOException {
//先读源文件的所有数据
List<String> list = Files.readAllLines(Paths.get("D:\\222.txt"));
list.forEach(System.out::println);
String[] arrs = list.toArray(new String[0]);
//再写文件
FileWriter fw=new FileWriter(new File("D:\\333.txt"));
//逐行写入时,修改源格式为目标格式
BufferedWriter bw=new BufferedWriter(fw);
for (String arr : arrs) {
String[] split = splitStrBySlash(arr);
String newData = split[0] + "," + split[1];
//换行写入
bw.write(newData + "\t\n");
}
System.out.println("写入文件完毕");
bw.close();
fw.close();
}
/**
* 使用"/"分割字符串,并只分割一次,转化为数组
*
* @param str 原字符串
* @return String[] 结果
*/
public static String[] splitStrBySlash(String str) {
String[] array = new String[2];
int indexFront = str.indexOf("/");
array[0] = str.substring(0, indexFront);
array[1] = str.substring(indexFront + 1);
return array;
}
public static void main(String[] args) throws IOException {
WriteFileByLineTest lineTest = new WriteFileByLineTest();
lineTest.test();
}
}