目前为止,我了解到只有两种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();
    }

}

Java ini文件读写修改配置内容以及使用org.dtools.javaini-v1.1.00.jar中文乱码相关推荐

  1. QSettings配置读写-win注册表操作-ini文件读写

    版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址: 本文标题:QSettings配置读写-win注册表操作-ini文件读写     本文地址:http:// ...

  2. 怎么把html转为ini,ini文件读写

    android编程ini文件读写 写了个android程序,想借助ini文件保存程序配置,供下次启动读取用,单android编程iniini文件读写的方法为: 一.将信息写入.INI文件中 1.所用的 ...

  3. java大文件读写操作

    转载自:http://blog.csdn.net/akon_vm/article/details/7429245 RandomAccessFile RandomAccessFile是用来访问那些保存数 ...

  4. win7 64位 安装java jdk1.8 ,修改配置环境变量

    下载jdk1.8,下载地址:http://www.wmzhe.com/soft-30118.html 安装时有两个程序,都安装在同一个目录下.   win7 64位 安装java jdk1.8 ,修改 ...

  5. C#InI文件读写剖析

    C#InI文件读写剖析 1.读取ini文件 StringBuilder stringBuilder = new StringBuilder();GetPrivateProfileString(sect ...

  6. Java写文件不覆盖原内容

    使用Java写文件不覆盖原有内容 public void writeToTXT(String str){FileOutputStream o = null;String path="Your ...

  7. 【Java】文件读写

    [Java]文件读写 FileInputStream类和FileOutputStream类 从文件读入全部数据 public static String readData(String filenam ...

  8. VC INI文件读写 和 GetProfileString,WriteProfileString函数的使用

    VC中用函数读写ini文件的方法 ini文件(即Initialization file),这种类型的文件中通常存放的是一个程序的初始化信息.ini文件由若干个节(Section)组成,每个Sectio ...

  9. VC++中实现INI文件读写的方法和示例

    一:读ini配置文件 DWORD GetPrivateProfileString(LPCTSTR lpAppName, LPCTSTR lpKeyName, LPCTSTR lpDefault, LP ...

  10. 数据库的备份与还原+INI文件数据库参数配置

    利用SQL语句来完成对SQL Server数据库的备份与还原功能 仅以练习 完成代码如下: ------------------------------ unit Unit1; interface u ...

最新文章

  1. 用ASP.NET建立一个在线RSS新闻聚合器(3)
  2. 超长数列中n个整数排序C++代码实现
  3. 最短路径问题的算法实现【转载】
  4. 用手动和自动分别实现使用其DVD安装盘作为本地yum源
  5. AKS开讲啦! | DevOps with AKS
  6. java人脸识别更新:摄像头支持360、火狐和谷歌浏览器
  7. Python项目实战
  8. Linux如何清除系统密码,如何消除LINUX系统密码
  9. word目录怎么跳转到相应页码_Word目录不会做?请看完整操作步骤
  10. mysql怎么判断多行数据日期是否连续_MySQL学习笔记(一)
  11. Motion 5 for Mac(专业视频编辑软件)v5.3.2永久破解版
  12. hive编程指南电子版_2020浙江省太阳能利用及节能技术重点实验室开放基金课题申请指南...
  13. Mac 环境下labelImg标注工具的安装
  14. trainNetwork - Matlab官网介绍的中文版
  15. 单片机python教程推荐_有Python基础的小白如何学习单片机?
  16. 【吴恩达】机器学习第16章异常检测以及ex8部分编程练习
  17. unlink php 实例,PHP unlink()用法及代碼示例
  18. 2019最新《炼数成金实战Java高并发程序设计+完整课件》
  19. SubstanceDesigner制作PBR材质制作并且同步到Unity小尝试
  20. Android作为客户端,PC作为服务端:实现网络通信

热门文章

  1. 计算机怎么审单流程,电子审单
  2. 新西兰 计算机 转专业,新西兰留学后如何转学转专业?
  3. 金融小白进阶记——金融加速器
  4. 浪潮云服务器安装win7系统,WIN7旗舰版操作系统中浪潮ERP_GS5.2安装说明.doc
  5. 平方根估计 python 3
  6. Tigase8 SSL安全连接配置与代码实现
  7. 小程序二维码和小程序带参数二维码生成
  8. 1048 习题4-4 三个整数求最大值
  9. Mysql各版本驱动包
  10. 医学图像分割——Unet