importorg.apache.commons.io.IOUtils;import java.io.*;importjava.nio.file.Files;importjava.nio.file.Paths;importjava.util.ArrayList;importjava.util.List;public classToDatasUtils {/*** 修改SM.dat、XE.dat中 1-10组棒位动态控制
*@parampath
*@paramlist*/
public static void toWriteUserTab(String path, Listlist){
FileReader in= null;
LineNumberReader reader= null;
File sourceFile= newFile(path);//内存流, 作为临时流
CharArrayWriter tempStream = null;
FileWriter out= null;try{if(!sourceFile.exists()){return;x
}//内存流, 作为临时流
tempStream = newCharArrayWriter();
in= newFileReader(sourceFile);
reader= newLineNumberReader(in);
String s= "";int dataIndex = 0;int lines = 0;while (s != null) {
lines++;
s=reader.readLine();if(lines <= 11){//将该行写入内存
tempStream.write(s);//添加换行符
tempStream.append(System.getProperty("line.separator"));
}else{//获取最后一部分开始的行数
if(s.contains("IMOV=")){
dataIndex=lines;break;
}
}
}//将需要的几个写入txt中去
for(String s1 : list) {
tempStream.write(" "+s1+",");
tempStream.append(System.getProperty("line.separator"));
}
lines= 0;
s= "";
in= newFileReader(sourceFile);
reader= newLineNumberReader(in);while (s != null) {
lines++;
s=reader.readLine();if(lines >= dataIndex && lines <=getFileLineNum(path)){//将该行写入内存
tempStream.write(s);//添加换行符
tempStream.append(System.getProperty("line.separator"));
}
}
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(in);
}catch(Exception e){
e.printStackTrace();
}finally{//将内存中的流 写入 文件
try{
out= newFileWriter(path);
tempStream.writeTo(out);
}catch(IOException e) {
e.printStackTrace();
}finally{
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(tempStream);
}
}
}//获取文本最大行数
public static longgetFileLineNum(String filePath) {try{returnFiles.lines(Paths.get(filePath)).count();
}catch(IOException e) {return -1;
}
}public static voidmain(String[] args) {
List dataList = new ArrayList<>();
dataList.add("1*-100,-90,4*0");
dataList.add("2*-100,-90,4*0");
dataList.add("3*-100,-90,4*0");
dataList.add("8*-100,-90,4*0");
dataList.add("8*-100,-90,4*0");
toWriteUserTab("C:\\Users\\lxp\\Desktop\\11\\SM.dat",dataList);
}
}