第二十篇-如何写配置文件
配置文件不同的格式所用不同函数,可能可以优化
WriteData.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.aimee.logtest; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public final class WriteData { private final String TAG = "WriteData"; public void writeCfgValue(String file, String section, String variable, String value) throws IOException { String fileContent, allLine, newLine; String getValue = null; File file1 = new File(file); if (!file1.exists()) { file1.createNewFile(); } String path_1 = file1.getParent(); String fileNew = path_1 + "/" + "tmp.ini"; File file_new = new File(fileNew); if (!file_new.exists()) { file_new.createNewFile(); } BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); Boolean canAdd = false; Boolean canAdd1 = false; Boolean title = false; fileContent = ""; Boolean tag=false; try { while ((allLine = bufferedReader.readLine()) != null) { Pattern p; Matcher m; p = Pattern.compile("\\[\\w+]"); m = p.matcher(allLine); if (m.matches()) { title = true; canAdd = false; canAdd1=false; p = Pattern.compile("\\[" + section + "]"); m = p.matcher(allLine); if (m.matches()) { canAdd = true; canAdd1=true; title = false; fileContent += allLine + "\r\n"; } } if (title && !canAdd) { fileContent += allLine + "\r\n"; } if (!title && canAdd) { Pattern p1; Matcher m1; p1 = Pattern.compile(".*?=.*?"); m1 = p1.matcher(allLine); if (m1.matches()) { String[] strArray = allLine.split("="); getValue = strArray[0].trim(); if (getValue.equalsIgnoreCase(variable)) { newLine = getValue + "=" + value; fileContent += newLine + "\r\n"; tag=true; canAdd1=false; } else{ fileContent+=allLine+"\r\n"; } } else{ if(allLine.equals("")){ if(canAdd1){ newLine = variable + "=" + value; fileContent+=newLine+"\r\n"; } fileContent+=allLine+"\r\n"; tag=true; canAdd1=false; } } } } if(fileContent.equals("")){ fileContent="["+section+"]"+"\r\n"; newLine = variable + "=" + value; fileContent+=newLine+"\r\n"; } else{ if(!canAdd&&!tag){ fileContent+="\r\n"+"["+section+"]"+"\r\n"; newLine = variable + "=" + value; fileContent+=newLine+"\r\n"; } if(canAdd1&&!tag){ newLine = variable + "=" + value; fileContent+=newLine+"\r\n"; } } } catch(IOException ex) { throw ex; }finally { bufferedReader.close(); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileNew, false)); bufferedWriter.write(fileContent); bufferedWriter.flush(); bufferedWriter.close(); } file_new.renameTo(file1); } @RequiresApi(api = Build.VERSION_CODES.N) public void writeCfgValue(String file, String section, String testitem, String sublocation, String min, String max, String expvalue1, String expcalue2, String actvalue1, String actvalue2, String status, String failinfo, String errorcode) throws IOException { String fileContent, allLine, newLine; String getValue = null; String[] arr={testitem,sublocation,min,max,expvalue1,expcalue2,actvalue1,actvalue2,status,failinfo,errorcode}; File file1 = new File(file); if (!file1.exists()) { file1.createNewFile(); } String path_1 = file1.getParent(); String fileNew = path_1 + "/" + "tmp.ini"; File file_new = new File(fileNew); if (!file_new.exists()) { file_new.createNewFile(); } BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); Boolean canAdd = false; Boolean canAdd1 = false; Boolean title = false; fileContent = ""; Boolean tag=false; try { while ((allLine = bufferedReader.readLine()) != null) { Pattern p; Matcher m; p = Pattern.compile("\\[\\w+]"); m = p.matcher(allLine); if (m.matches()) { title = true; canAdd = false; canAdd1=false; p = Pattern.compile("\\[" + section + "]"); m = p.matcher(allLine); if (m.matches()) { canAdd = true; canAdd1=true; title = false; fileContent += allLine + "\r\n"; } } if (title && !canAdd) { fileContent += allLine + "\r\n"; } if (!title && canAdd) { if (allLine.contains(",")) { String[] strArray = allLine.split(","); getValue = strArray[0].trim(); if (getValue.equalsIgnoreCase(testitem)) { newLine= Arrays.stream(arr).collect(Collectors.joining(",")); fileContent += newLine + "\r\n"; tag=true; canAdd1=false; } else{ fileContent+=allLine+"\r\n"; } } else{ if(allLine.equals("")){ if(canAdd1){ newLine= Arrays.stream(arr).collect(Collectors.joining(",")); fileContent+=newLine+"\r\n"; } fileContent+=allLine+"\r\n"; tag=true; canAdd1=false; } } } } if(fileContent.equals("")){ fileContent="["+section+"]"+"\r\n"; newLine= Arrays.stream(arr).collect(Collectors.joining(",")); fileContent+=newLine+"\r\n"; } else{ if(!canAdd&&!tag){ fileContent+="\r\n"+"["+section+"]"+"\r\n"; newLine= Arrays.stream(arr).collect(Collectors.joining(",")); fileContent+=newLine+"\r\n"; } if(canAdd1&&!tag){ newLine= Arrays.stream(arr).collect(Collectors.joining(",")); fileContent+=newLine+"\r\n"; } } } catch(IOException ex) { throw ex; }finally { bufferedReader.close(); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileNew, false)); Log.i(TAG, "fileContent: "+fileContent); bufferedWriter.write(fileContent); bufferedWriter.flush(); bufferedWriter.close(); } file_new.renameTo(file1); } }
MainActivity.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.aimee.logtest; import android.Manifest; import android.content.pm.PackageManager; import android.os.Build; import android.os.Environment; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import java.io.File; import java.io.IOException; public class MainActivity extends AppCompatActivity { String path_directory; String file_name; private final int REQUESTCODE=101; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); path_directory = Environment.getExternalStorageDirectory().getAbsolutePath(); path_directory=path_directory+"/"+"save"; file_name = "test4.log"; String path=path_directory+"/"+file_name; if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){ int checkSelfPermission=checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE); if(checkSelfPermission==PackageManager.PERMISSION_DENIED){ requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUESTCODE); } } fileMethodSet fileMethodSet=new fileMethodSet(); File file=new File(path); if(!file.exists()){ try { fileMethodSet.create_file(path_directory,file_name); } catch (IOException e) { e.printStackTrace(); } } WriteData writeData=new WriteData(); try { // writeData.writeCfgValue(path,"HEAD1","NAME2","start5"); writeData.writeCfgValue(path,"TESTITEM","cpu111","j08","1004","3004","","","1004","","PASS","",""); } catch (IOException e) { e.printStackTrace(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){ super.onRequestPermissionsResult(requestCode,permissions,grantResults); if(requestCode==REQUESTCODE){ if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[0]== PackageManager.PERMISSION_GRANTED){ Toast.makeText(this,"ok",Toast.LENGTH_LONG).show(); }else { Toast.makeText(this,"无权限",Toast.LENGTH_LONG).show(); } } } }
可以写入log文件,不过只限于等于和逗号两类。
简化版,使用不定长参数,可以实现模块的添加,修改,如果后续添加新的测试项目,提供不同参数,只需在后面添加相应参数条件函数,不需动以前的函数。
ConfigFileSet.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.aimee.logtest; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public final class ConfigFileSet { // private final String TAG = "WriteData"; private String newLine; private String fileContent, allLine;//定义待写入内容和读取的每一行的变量 private String getValue = null;//定义每一行的第一个字符串 private Boolean canAdd = false; private Boolean canAdd1 = false; Boolean title = false; private Boolean tag=false; @RequiresApi(api = Build.VERSION_CODES.N) public void writeCfgValue(String file, String section, String... values) throws IOException { // Log.i(TAG, "value_length: "+values.length); fileContent = ""; newLine=getNewLine(values);//获取要添加或替换的字符串 String fileNew=create_file(file);//获取文件的临时存放目录以及创建文件 File file1=new File(file);//读取文件对象 File file_new=new File(fileNew);//写入文件对象 BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); try { while ((allLine = bufferedReader.readLine()) != null) { fileContent=write_title(section); if (title && !canAdd) { fileContent += allLine + "\r\n"; } if (!title && canAdd) { fileContent=write_replace_body(values); } } if(fileContent.equals("")){ fileContent="["+section+"]"+"\r\n"; fileContent+=newLine+"\r\n"; } else{ if(!canAdd&&!tag){ fileContent+="\r\n"+"["+section+"]"+"\r\n"; fileContent+=newLine+"\r\n"; } if(canAdd1&&!tag){ fileContent+=newLine+"\r\n"; } } } catch(IOException ex) { throw ex; }finally { bufferedReader.close(); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileNew, false)); bufferedWriter.write(fileContent); bufferedWriter.flush(); bufferedWriter.close(); } file_new.renameTo(file1); } @RequiresApi(api = Build.VERSION_CODES.N) private String getNewLine(String[] values){ if(values.length==2){ newLine = values[0] + "=" + values[1]; } if(values.length==11){ String[] arr=new String[11]; for(int i=0;i<11;i++){ arr[i]=values[i]; } newLine=Arrays.stream(arr).collect(Collectors.joining(",")); } return newLine; } private String create_file(String file) throws IOException { File file1 = new File(file); if (!file1.exists()) { file1.createNewFile(); } String path_1 = file1.getParent(); String fileNew = path_1 + "/" + "tmp.ini"; File file_new = new File(fileNew); if (!file_new.exists()) { file_new.createNewFile(); } return fileNew; } private String write_title(String section){ Pattern p; Matcher m; p = Pattern.compile("\\[\\w+]"); m = p.matcher(allLine); if (m.matches()) { title = true; canAdd = false; canAdd1=false; p = Pattern.compile("\\[" + section + "]"); m = p.matcher(allLine); if (m.matches()) { canAdd = true; canAdd1=true; title = false; fileContent += allLine + "\r\n"; } } return fileContent; } private String write_replace_body(String[] values){ if(values.length==2) { Pattern p1; Matcher m1; p1 = Pattern.compile(".*?=.*?"); m1 = p1.matcher(allLine); if (m1.matches()) { String[] strArray = allLine.split("="); getValue = strArray[0].trim(); if (getValue.equalsIgnoreCase(values[0])) { fileContent += newLine + "\r\n"; tag = true; canAdd1 = false; } else { fileContent += allLine + "\r\n"; } } else { if (allLine.equals("")) { if (canAdd1) { fileContent += newLine + "\r\n"; } fileContent += allLine + "\r\n"; tag = true; canAdd1 = false; } } } if(values.length==11){ if (allLine.contains(",")) { String[] strArray = allLine.split(","); getValue = strArray[0].trim(); if (getValue.equalsIgnoreCase(values[0])) { fileContent += newLine + "\r\n"; tag=true; canAdd1=false; } else{ fileContent+=allLine+"\r\n"; } } else{ if(allLine.equals("")){ if(canAdd1){ fileContent+=newLine+"\r\n"; } fileContent+=allLine+"\r\n"; tag=true; canAdd1=false; } } } return fileContent; } }
优点:模块化,易阅读,另,可以用Log.i进行debug,在LogCat下搜索类名找到相应log。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.aimee.logtest; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public final class ConfigFileSet { // private final String TAG = "WriteData"; private String newLine; private String fileContent, allLine;//定义待写入内容和读取的每一行的变量 private String getValue = null;//定义每一行的第一个字符串 private Boolean canAdd = false; private Boolean canAdd1 = false; Boolean title = false; private Boolean tag=false; private Boolean tag1=true; @RequiresApi(api = Build.VERSION_CODES.N) public void writeCfgValue(String file, String section, String... values) throws IOException { // Log.i(TAG, "value_length: "+values.length); fileContent = ""; newLine=getNewLine(values);//获取要添加或替换的字符串 String fileNew=create_file(file);//获取文件的临时存放目录以及创建文件 File file1=new File(file);//读取文件对象 File file_new=new File(fileNew);//写入文件对象 BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); try { while ((allLine = bufferedReader.readLine()) != null) { fileContent=write_title(section); if (title && !canAdd) { fileContent += allLine + "\r\n"; } if (!title && canAdd) { fileContent=write_replace_body(values); } } if(fileContent.equals("")){ fileContent="["+section+"]"+"\r\n"; fileContent+=newLine+"\r\n"; } else{ if(!canAdd&&!tag){ fileContent+="\r\n"+"["+section+"]"+"\r\n"; if(section=="TESTITEM"&&tag1){ String x="testitem, sublocation, min, max, expvalue1, expcalue2, actvalue1, actvalue2, status, failinfo, errorcode".toUpperCase(); fileContent+=x+"\r\n"; tag1=false; } fileContent+=newLine+"\r\n"; } if(canAdd1&&!tag){ fileContent+=newLine+"\r\n"; } } } catch(IOException ex) { throw ex; }finally { bufferedReader.close(); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileNew, false)); bufferedWriter.write(fileContent); bufferedWriter.flush(); bufferedWriter.close(); } file_new.renameTo(file1); } @RequiresApi(api = Build.VERSION_CODES.N) private String getNewLine(String[] values){ if(values.length==2){ newLine = values[0] + "=" + values[1]; } if(values.length==11){ String[] arr=new String[11]; for(int i=0;i<11;i++){ arr[i]=values[i]; } newLine=Arrays.stream(arr).collect(Collectors.joining(",")); } return newLine; } private String create_file(String file) throws IOException { File file1 = new File(file); if (!file1.exists()) { file1.createNewFile(); } String path_1 = file1.getParent(); String fileNew = path_1 + "/" + "tmp.ini"; File file_new = new File(fileNew); if (!file_new.exists()) { file_new.createNewFile(); } return fileNew; } private String write_title(String section){ Pattern p; Matcher m; p = Pattern.compile("\\[\\w+]"); m = p.matcher(allLine); if (m.matches()) { title = true; canAdd = false; canAdd1=false; p = Pattern.compile("\\[" + section + "]"); m = p.matcher(allLine); if (m.matches()) { canAdd = true; canAdd1=true; title = false; fileContent += allLine + "\r\n"; } } return fileContent; } private String write_replace_body(String[] values){ if(values.length==2) { Pattern p1; Matcher m1; p1 = Pattern.compile(".*?=.*?"); m1 = p1.matcher(allLine); if (m1.matches()) { String[] strArray = allLine.split("="); getValue = strArray[0].trim(); if (getValue.equalsIgnoreCase(values[0])) { fileContent += newLine + "\r\n"; tag = true; canAdd1 = false; } else { fileContent += allLine + "\r\n"; } } else { if (allLine.equals("")) { if (canAdd1) { fileContent += newLine + "\r\n"; } fileContent += allLine + "\r\n"; tag = true; canAdd1 = false; } } } if(values.length==11){ if (allLine.contains(",")) { String[] strArray = allLine.split(","); getValue = strArray[0].trim(); if (getValue.equalsIgnoreCase(values[0])) { fileContent += newLine + "\r\n"; tag=true; canAdd1=false; } else{ fileContent+=allLine+"\r\n"; } } else{ if(allLine.equals("")){ if(canAdd1){ fileContent+=newLine+"\r\n"; } fileContent+=allLine+"\r\n"; tag=true; canAdd1=false; } } } return fileContent; } }