package TESTtxt;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import BasicFileFuntion.BasicFileFuntion;
/********************修改前的内容*********************
电视:
{00,11,22,33,44,55,66,aa,bb,cc},
{00,12,12,23,34,45,56,67,67,78},
.
.
.
空调:
{ab,ac,ad,ae,af,12,23,34,45,55},
{aa,bb,cc,dd,ee,ff,11,22,33,44},
.
.
.
*************************************************/
/********************修改后的内容*********************
电视:
{0x00,0x11,0x22,0x33,0x44,0x55,0x66,0xaa,0xbb,0xcc},
{0x00,0x12,0x12,0x23,0x34,0x45,0x56,0x67,0x67,0x78},
.
.
.
空调:
{0xab,0xac,0xad,0xae,0xaf,0x12,0x23,0x34,0x45,0x55},
{0xaa,0xbb,0xcc,0xdd,0xee,0xff,0x11,0x22,0x33,0x44},
.
.
.
*************************************************/
public class TESTtxt {
public static void main(String[] args){
/*修改指定txt文本的内容,并保存在一个新的文件中*/
File fr8 = new File("D:\\work-pc\\Program Files\\Java\\workspace\\TESTtxt\\123.txt");
if(fr8.exists()&&fr8.isFile()){//判断文件是否存在
System.out.println("从文件fr123.txt中读取数据:");
}else{
System.out.println("文件123.txt不存在,程序结束!");
return;
}
try{//以下为读取文件操作,分为5步,同样操作代码放入try-catch语句中
File fr10 = BasicFileFuntion.createFile("D:\\work-pc\\Program Files\\Java\\workspace\\TESTtxt\\fr10.txt");//创建用于保存数据的文件
//写入准备
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("D:\\work-pc\\Program Files\\Java\\workspace\\TESTtxt\\fr10.txt")));
FileReader fr9 = new FileReader(fr8); //1.创建一个读文件对象,准备读取文件
BufferedReader br1 = new BufferedReader(fr9);//2.创建一个BufferedReader对象,用于读取一行数据
StringBuilder sb = new StringBuilder();//写操作时使用,字符串大小无上限
String str1 = null;
Pattern p = Pattern.compile("\\{");//用于匹配的正则
Matcher m = null;
List<String> list=new ArrayList<String>();//list用于存储一行的元素
while((str1 = br1.readLine()) != null){//依次读取一行数据
m = p.matcher(str1); //进行匹配
if((m.find())){ //查找是否匹配到正则表达式
StringTokenizer st=new StringTokenizer(str1,",");
String str2 = null;
while(st.hasMoreTokens()){
list.add(st.nextToken());
}
str2 = list.get(0);//取出第一个需要修改的元素
str2 = str2.substring(1);//获得子集
list.set(0, str2);//替换
sb.append("{");//重新组合数据
for(String s: list){//处理一行数据
sb.append("0x" + s + ",");//加入sb字符串中
}
list.clear();
sb.append("\r\n");//换行符
}else{
sb.append(str1);//添加到sb
sb.append("\r\n");//换行符
}
}
out.write(sb.toString());//一次性写入
out.flush();
out.close();
System.out.print(fr10.getName() + "文件写入完毕!");
fr9.close();//4.关闭读文件对象,释放资源
br1.close();//5.关闭读文件对象缓冲区,释放资源
}catch(FileNotFoundException e){//它要放在IOException之前,否则将被覆盖出错
System.out.println("出现错误,错误信息为:"+e.getLocalizedMessage());
}catch(IOException e){
System.out.println("出现错误信息,错误信息为:"+e.getLocalizedMessage());
}
}
}
修改txt文档的内容并保存在新的txt文档中
最新推荐文章于 2023-02-09 19:49:35 发布