JAVA實現ini檔案的讀寫功能
阿新 • • 發佈:2020-12-21
背景
公司老闆希望匯出單個客戶資料,以前看過ini格式的內容輸出,優點整潔、能清晰看到內容,所以當場就決定通過該方式輸出,老闆看到後挺滿意的
1.展示效果
2.呼叫方式
public static void main(String[] args) throws IOException {
File file = new File("d:\\a.ini");
if(!file.exists())file.createNewFile();
//寫入功能
write (file.getAbsolutePath(),"基本資訊","姓名","張三");
write(file.getAbsolutePath(),"基本資訊","性別","男");
write(file.getAbsolutePath(),"基本資訊","年齡","18");
write(file.getAbsolutePath(),"基本資訊","生日" ,"1998-08-18");
write(file.getAbsolutePath(),"基本資訊","家長","張帥");
//讀取並輸出到控制檯
System.out.println(read(file.getAbsolutePath(),"基本資訊","生日"));
}
3.工具類原始碼
package com.yanping;
import org.apache.commons.lang.StringUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class IniUtils {
public static void main(String[] args) throws IOException {
File file = new File("d:\\a.ini");
if(!file.exists())file.createNewFile();
//寫入功能
write(file.getAbsolutePath(),"基本資訊","姓名","張三");
write(file.getAbsolutePath(),"基本資訊","性別","男");
write(file.getAbsolutePath(),"基本資訊","年齡","18");
write(file.getAbsolutePath(),"基本資訊","生日","1998-08-18");
write(file.getAbsolutePath(),"基本資訊","家長","張帥");
//讀取並輸出到控制檯
System.out.println(read(file.getAbsolutePath(),"基本資訊","生日"));
}
/**
* 根據section及key值讀取ini檔案的值
* @param filename ini檔名
* @param section 塊名稱:eg 讀取[基本資訊],只需傳入"基本資訊"即可
* @param key
* @return key對應的value
* @throws IOException
*/
public static String read(String filename,String section,String key) throws IOException {
return read(filename,section,key,null);
}
/**
* 根據section及key值讀取ini檔案的值
* @param filename ini檔名
* @param section 塊名稱:eg 讀取[基本資訊],只需傳入"基本資訊"即可
* @param key
* @param defaultValue 當配置檔案中不存在key時 返回的預設值
* @return key對應的value
* @throws IOException
*/
public static String read(String filename,String section,String key,String defaultValue) throws IOException {
String value = null;
File file = FileUtils.getFile(filename);
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(file))){
String line = null;
String sectionLineRegex = "\\[.*\\]",sectionRegex = String.format("\\[%s\\]",section);
String keyLineRegex = String.format("%s\\s*=\\s*.*",key),keyRegex = String.format("%s\\s*=\\s*",key);
boolean active=false;
while ((line=bufferedReader.readLine())!=null){
line = StringUtils.trimToEmpty(line);
if(line.matches(sectionLineRegex)){
if(line.matches(sectionRegex)){
active=true;
}else{
active=false;
}
}
if(active&&line.matches(keyLineRegex)){
value = line.replaceFirst(keyRegex,"");
break;
}
}
return value==null?defaultValue:value;
}
}
/**
* 寫入配置
* @param filename 檔名稱
* @param section 模組名稱
* @param key 鍵
* @param value 值
* @throws IOException
*/
public static void write(String filename,String section,String key,String value) throws IOException {
List<String> lines = getLines(filename);
int sectionIndex = hasSection(lines,section);
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filename))) {
if (sectionIndex>-1) {
Integer[] integers = getKeyIndex(lines,section,key);
int size = lines.size();
if (integers == null||integers.length==0) {
int addIndex=getWriteIndex(lines,section);//sectionIndex+1;
if(addIndex>=size){
lines.add(String.format("%s=%s", key, value));
}else{
lines.add(addIndex,String.format("%s=%s", key, value));
}
} else {
String line = null;
String valueRegex = "=.*";
for (Integer index:integers) {
line = lines.remove(index.intValue());
line = line.replaceFirst(valueRegex,String.format("=%s",value));
lines.add(index.intValue(),line);
}
}
} else {
int size = lines.size();
lines.add(size++,String.format("[%s]", section));
lines.add(size++,String.format("%s=%s", key, value));
}
bufferedWriter.write(lines.get(0));
for (int i = 1; i < lines.size(); i++) {
bufferedWriter.newLine();
bufferedWriter.write(lines.get(i));
}
}
}
/**
* 獲取配置檔案中所有行
* @param filename
* @return
* @throws IOException
*/
private static List<String> getLines(String filename) throws IOException {
List<String> lines = new ArrayList<>();
File file = FileUtils.getFile(filename);
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(file))){
String line = null;
while ((line=bufferedReader.readLine())!=null){
lines.add(StringUtils.trimToEmpty(line));
}
return lines;
}
}
/**
* 檢視配置檔案中是否存在section模組
* @param lines
* @param section
* @return -1或模組第一個所在行下標
* @throws IOException
*/
private static int hasSection(List<String> lines,String section) throws IOException {
String sectionLineRegex = "\\[.*\\]", sectionRegex = String.format("\\[%s\\]", section);
int sectionIndex = -1, currentIndex = 0;
for (String line:lines) {
line = StringUtils.trimToEmpty(line);
if (line.matches(sectionLineRegex)) {
if (line.matches(sectionRegex)) {
sectionIndex = currentIndex;
break;
}
}
currentIndex++;
}
return sectionIndex;
}
/**
* 獲取key值的行下標
* @param lines
* @param section
* @param key
* @return
* @throws IOException
*/
private static Integer[] getKeyIndex(List<String> lines, String section, String key) throws IOException {
List<Integer> keyIndex = new ArrayList<>();
String value = null;
int index = 0, currentIndex = 0;
String sectionLineRegex = "\\[.*\\]", sectionRegex = String.format("\\[%s\\]", section);
String keyLineRegex = String.format("%s\\s*=\\s*.*", key), keyRegex = String.format("%s\\s*=\\s*", key);
boolean active = false;
for (String line:lines) {
if (line.matches(sectionLineRegex)) {
if (line.matches(sectionRegex)) {
active = true;
} else {
active = false;
}
}
if (active && line.matches(keyLineRegex)) {
index = currentIndex;
keyIndex.add(index);
}
currentIndex++;
}
Integer[] ints = new Integer[keyIndex.size()];
keyIndex.toArray(ints);
return ints;
}
/**
* 獲取寫入行下標
* @param lines
* @param section
* @return
*/
private static int getWriteIndex(List<String> lines,String section){
int writeIndex = -1;
boolean active = false;
String sectionLineRegex = "\\[.*\\]",sectionRegex = String.format("\\[%s\\]", section);
for (int i=0;i<lines.size();i++) {
if(lines.get(i).matches(sectionRegex)){
active=true;
}else if(active&&lines.get(i).matches(sectionRegex)){
writeIndex = i;
break;
}
}
return writeIndex==-1?lines.size():writeIndex;
}
}