gpt4 book ai didi

java - 将 Java 属性文件转换为 JSON 字符串

转载 作者:行者123 更新时间:2023-11-29 03:30:33 24 4
gpt4 key购买 nike

我正在编写一个简单的解析器来将包含 name=value 对中的条目的 java 属性文件转换为 json 字符串。下面是代码。该代码要求每个条目都在一个新行中:

      sCurrentLine = br.readLine();
while ((sCurrentLine) != null)
{
config+=sCurrentLine.replace('=', ':');
sCurrentLine = br.readLine()
if(sCurrentLine!=null)
config+=",";
}
config+="}";

该函数工作正常,除非属性文件中有额外的空新行。 (例如:假设我在 props 文件中写入最后一个条目,然后按两次输入,文件将在最后一个条目之后包含两个空的新行)。虽然预期的输出是 {name1:value1,name2:value2} ,但在上述情况下,当存在额外的新行时,我得到的输出是 {name1:value1,name2:value2, 。尾随 , 的数量随着空新行的数量而增加。

我知道这是因为 readLine() 读取了空行,而逻辑上它不应该读取空行,但我该如何更改它?

最佳答案

这可以使用 contains() 方法解决。只需确保您的行中存在 "="..

while ((sCurrentLine) != null)
{
if(sCurrentLine.contains("=") {
config+=sCurrentLine.replace('=', ':');
sCurrentLine = br.readLine()
if(sCurrentLine!=null)
config+=",";
}
}

示例

sCurrentLine = "name=dave"
if(sCurrentLine.contains("=")) // Evaluates to true.
// Do logic.

sCurrentLine = ""
if(sCurrentLine.contains("=")) // Evaluates to false.
// Don't do logic.

sCurrentLine = "\n"
if(sCurrentLine.contains("=")) // Evaluates to false.
// Don't do logic.

I know its because the readLine() reads the empty line while logically it shouldn't but how do I change this?

readLine() 读取所有内容直到 \n。这就是它检查新行的方式。你有 \n 而在它之前没有任何内容,所以你的行将由 "" 组成,因为 \n 被省略了。

略微增强

如果你想确保你的行中肯定有一个名称和一个属性,那么你可以使用一些简单的正则表达式。

if(s.CurrentLine.matches("\\w+=\\w+"))
// Evaluates to any letter, 1 or moe times, followd by an "=", followed by letters.

关于java - 将 Java 属性文件转换为 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18507067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com