目前为止,我了解到只有两种INI文件读取的jar包,分别为ini4j-0.5.4.jar和org.dtools.javaini-v1.1.00.jar
我只简单描述一下org.dtools.javaini-v1.1.00.jar的使用以及中文乱码问题。
简单使用如下:
public class TestDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String fileName = "D:\\test.ini";
File file = new File(fileName);
IniFile iniFile = new BasicIniFile();
//读取INI文件
IniFileReader rad = new IniFileReader(iniFile, file);
rad.read();
//写入INI文件
IniFileWriter wir = new IniFileWriter(iniFile, file);
IniSection iniSection = iniFile.getSection("user");
IniItem iniItemUserName = iniSection.getItem("user_name");
IniItem iniItemUserId = iniSection.getItem("user_id");
IniItem iniItemUserAge = iniSection.getItem("user_age");
IniItem iniItemDepartment = iniSection.getItem("department");
System.out.println("name:"+iniItemUserName.getValue());
System.out.println("name:"+iniItemUserId.getValue());
System.out.println("name:"+iniItemUserAge.getValue());
System.out.println("name:"+iniItemDepartment.getValue());
iniItemUserName.setValue("李四");
iniItemUserId.setValue("0002");
iniItemUserAge.setValue(23);
iniItemDepartment.setValue("销售部");
wir.write();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
INI文件内容是:
[user]
user_name=张三
user_id=0001
user_age=22
department=技术部
运行代码之后INI文件变成:
[user]
user_name=李四
user_id=0002
user_age=23
department=销售部
我们可以通过网上下载org.dtools.javaini-v1.1.00.jar导入项目,使用的时候会出现中文乱码,这是什么情况呢?
通过查看org.dtools.javaini-v1.1.00.jar的源码,原来他们使用是了ASCII编码。主要通过查看这两个类IniFileReader类和IniFileWriter类。
读取INI文件查看IniFileReade类,主要看的部分代码
public void read() throws IOException {
IniSection currentSection = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(this.file), "ASCII"));
省掉部分代码
reader.close();
}
从这段BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(this.file), "ASCII"));代码就可以知道读取INI文件的格式是ASCII。所以我们需要改成utf-8或者GBK才不会出现中文乱码。
写入INI文件看IniFileWriter主要看代码部分
public void write() throws IOException {
BufferedWriter bufferWriter = null;
FileOutputStream fos = new FileOutputStream(this.file);
OutputStreamWriter osw = new OutputStreamWriter(fos, "ASCII");
bufferWriter = new BufferedWriter(osw);
bufferWriter.write(this.iniToString(this.ini));
bufferWriter.close();
}
这句代码 OutputStreamWriter osw = new OutputStreamWriter(fos, "ASCII");就可以知道写入INI文件的格式是ASCII,所以也会出现中文乱码。其实IniFileWriter类还有这句代码public static final String ENCODING = "ASCII";也是使用到ASCII,只是它不影响读写。
修改方式:
第一种方式下载源码进修改。源码只需要改这个public static final String ENCODING = "ASCII"代码就可以了,其它两个地方都是调用它。
第二种方式:分别生成一个类把里面的代码复制出来修改就行了。主要原因是因为里面的一些方法使用了private,所以只能复制了。如
public class MyIniFileReader extends IniFileReader {
private File file;
private IniFile ini;
static String getEndLineComment(String line) {
if (!isSection(line) && !isItem(line)) {
throw new FormatException("getEndLineComment(String) is unable to return the comment from the given string (\"" + line + "\" as it is not an item nor a section.");
} else {
int pos = line.indexOf(59);
return pos == -1 ? "" : line.substring(pos + 1).trim();
}
}
static String getItemName(String line) {
if (!isItem(line)) {
throw new FormatException("getItemName(String) is unable to return the name of the item as the given string (\"" + line + "\" is not an item.");
} else {
int pos = line.indexOf(61);
return pos == -1 ? "" : line.substring(0, pos).trim();
}
}
static String getItemValue(String line) {
if (!isItem(line)) {
throw new FormatException("getItemValue(String) is unable to return the value of the item as the given string (\"" + line + "\" is not an item.");
} else {
int posEquals = line.indexOf(61);
int posComment = line.indexOf(59);
if (posEquals == -1) {
return posComment == -1 ? line : line.substring(0, posComment).trim();
} else {
return posComment == -1 ? line.substring(posEquals + 1).trim() : line.substring(posEquals + 1, posComment).trim();
}
}
}
static String getSectionName(String line) {
if (!isSection(line)) {
throw new FormatException("getSectionName(String) is unable to return the name of the section as the given string (\"" + line + "\" is not a section.");
} else {
int firstPos = line.indexOf(91);
int lastPos = line.indexOf(93);
return line.substring(firstPos + 1, lastPos).trim();
}
}
static boolean isComment(String line) {
line = line.trim();
if (line.isEmpty()) {
return false;
} else {
char firstChar = line.charAt(0);
return firstChar == ';';
}
}
static boolean isItem(String line) {
line = removeComments(line);
if (line.isEmpty()) {
return false;
} else {
int pos = line.indexOf(61);
if (pos != -1) {
String name = line.substring(0, pos).trim();
return name.length() > 0;
} else {
return false;
}
}
}
static boolean isSection(String line) {
line = removeComments(line);
if (line.isEmpty()) {
return false;
} else {
char firstChar = line.charAt(0);
char lastChar = line.charAt(line.length() - 1);
return firstChar == '[' && lastChar == ']';
}
}
static String removeComments(String line) {
return line.contains(String.valueOf(';')) ? line.substring(0, line.indexOf(59)).trim() : line.trim();
}
public MyIniFileReader(IniFile ini, File file) {
super(ini, file);
if (ini == null) {
throw new NullPointerException("The given IniFile cannot be null.");
} else if (file == null) {
throw new NullPointerException("The given File cannot be null.");
} else {
this.file = file;
this.ini = ini;
}
}
public void read() throws IOException {
IniSection currentSection = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(this.file), "GB2312"));
String comment = "";
Object lastCommentable = null;
String line;
while((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
if (!comment.isEmpty() && lastCommentable != null) {
((Commentable)lastCommentable).setPostComment(comment);
comment = "";
}
} else {
String itemName;
if (isComment(line)) {
itemName = line.substring(1).trim();
if (comment.isEmpty()) {
comment = itemName;
} else {
comment = comment + "\n" + itemName;
}
} else {
String itemValue;
if (isSection(line)) {
itemName = getSectionName(line);
itemValue = getEndLineComment(line);
if (this.ini.hasSection(itemName)) {
currentSection = this.ini.getSection(itemName);
} else {
currentSection = this.ini.addSection(itemName);
}
currentSection.setEndLineComment(itemValue);
if (!comment.isEmpty()) {
currentSection.setPreComment(comment);
comment = "";
}
lastCommentable = currentSection;
} else if (isItem(line)) {
if (currentSection == null) {
throw new FormatException("An Item has been read,before any section.");
}
itemName = getItemName(line);
itemValue = getItemValue(line);
String endLineComment = getEndLineComment(line);
IniItem item;
if (currentSection.hasItem(itemName)) {
item = currentSection.getItem(itemName);
} else {
try {
item = currentSection.addItem(itemName);
} catch (InvalidNameException var11) {
throw new FormatException("The string \"" + itemName + "\" is an invalid name for an " + "IniItem.");
}
}
item.setValue(itemValue);
item.setEndLineComment(endLineComment);
if (!comment.isEmpty()) {
item.setPreComment(comment);
comment = "";
}
lastCommentable = item;
}
}
}
}
if (!comment.isEmpty() && lastCommentable != null) {
((Commentable)lastCommentable).setPostComment(comment);
comment = "";
}
reader.close();
}
}
public class MyIniFileWriter extends IniFileWriter {
private IniFile ini;
private File file;
private boolean sectionLineSeparator;
private boolean includeSpaces;
private boolean itemLineSeparator;
public MyIniFileWriter(IniFile ini, File file) {
super(ini, file);
if (ini == null) {
throw new IllegalArgumentException("Cannot write a null IniFile");
} else if (file == null) {
throw new IllegalArgumentException("Cannot write an IniFile to a null file");
} else {
this.ini = ini;
this.file = file;
this.setIncludeSpaces(false);
this.setItemLineSeparator(false);
this.setSectionLineSeparator(false);
}
}
@Override
public void write() throws IOException {
super.write();
BufferedWriter bufferWriter = null;
FileOutputStream fos = new FileOutputStream(this.file);
OutputStreamWriter osw = new OutputStreamWriter(fos, "GB2312");
bufferWriter = new BufferedWriter(osw);
bufferWriter.write(this.iniToString(this.ini));
bufferWriter.close();
}
private String iniToString(IniFile ini) {
StringBuilder builder = new StringBuilder();
int size = ini.getNumberOfSections();
for(int i = 0; i < size; ++i) {
IniSection section = ini.getSection(i);
builder.append(this.sectionToString(section));
builder.append("\r\n");
}
return builder.toString();
}
private String sectionToString(IniSection section) {
StringBuilder builder = new StringBuilder();
if (this.sectionLineSeparator) {
builder.append("\r\n");
}
String comment = section.getPreComment();
if (!comment.equals("")) {
builder.append(this.formatComment(comment, false));
}
builder.append("[" + section.getName() + "]");
comment = section.getEndLineComment();
if (!comment.equals("")) {
builder.append(" ;" + comment);
}
comment = section.getPostComment();
if (!comment.equals("")) {
builder.append(this.formatComment(comment, true));
builder.append("\r\n");
} else if (this.sectionLineSeparator) {
builder.append("\r\n");
}
int size = section.getNumberOfItems();
for(int i = 0; i < size; ++i) {
IniItem item = section.getItem(i);
builder.append("\r\n");
builder.append(this.itemToString(item));
}
return builder.toString();
}
private String formatComment(String comment, boolean prefixNewLine) {
StringBuilder sb = new StringBuilder();
if (comment.contains("\n")) {
String[] comments = comment.split("\n");
String[] var8 = comments;
int var7 = comments.length;
for(int var6 = 0; var6 < var7; ++var6) {
String aComment = var8[var6];
if (prefixNewLine) {
sb.append("\r\n");
}
sb.append(';' + aComment);
if (!prefixNewLine) {
sb.append("\r\n");
}
}
} else {
if (prefixNewLine) {
sb.append("\r\n");
}
sb.append(';' + comment);
if (!prefixNewLine) {
sb.append("\r\n");
}
}
return sb.toString();
}
private String itemToString(IniItem item) {
StringBuilder builder = new StringBuilder();
String comment = item.getPreComment();
if (!comment.equals("")) {
builder.append(this.formatComment(comment, false));
}
if (this.includeSpaces) {
builder.append(item.getName() + " = ");
} else {
builder.append(item.getName() + "=");
}
if (item.getValue() != null) {
builder.append(item.getValue());
}
if (!item.getEndLineComment().equals("")) {
builder.append(" ;" + item.getEndLineComment());
}
comment = item.getPostComment();
if (!comment.equals("")) {
builder.append(this.formatComment(comment, true));
builder.append("\r\n");
} else if (this.itemLineSeparator) {
builder.append("\r\n");
}
return builder.toString();
}
}