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

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

}
 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
错误"libicui18n.so.66: cannot open shared object file: No such file or directory"指的是在加载共享库libicui18n.so.66时找不到文件或目录。根据引用和引用的信息,这个错误通常发生在运行dtools或php-fpm时。 解决这个问题的方法之一是安装缺少的文件。根据引用,你可以使用wget命令下载缺少的文件libicu55_55.1-7_amd64.deb,并使用dpkg命令进行安装。这将提供所需的共享库文件。 请按照以下步骤操作: 1. 运行以下命令下载缺少的文件: ``` wget http://security.ubuntu.com/ubuntu/pool/main/i/icu/libicu55_55.1-7_amd64.deb ``` 2. 运行以下命令进行安装: ``` sudo dpkg -i libicu55_55.1-7_amd64.deb ``` 完成以上步骤后,应该能够解决"libicui18n.so.66: cannot open shared object file: No such file or directory"错误。重新运行dtools或php-fpm时,应该能够正确加载所需的共享库文件。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [dtools: error while loading shared libraries: libicui18n.so.55: cannot open shared object file](https://blog.csdn.net/u012478275/article/details/120062377)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [宝塔安装php遇错libicui18n.so.42: cannot open shared object file: No such file or directory](https://blog.csdn.net/sayyy/article/details/114403253)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值