java - 从文本文件获取输入并返回 json 字符串的程序

标签 java json filereader

这是我的文本文件的示例

JUNE 15
 Wednesday
BH 259: Trusting Jesus
TRUSTING GOD
Text: Hebrews 11:7-12

RBT: 1 Chron. 14-15;
John 18:19-40

By faith Abraham, when called to go to a place he would later
receive as his inheritance, obeyed and went, even though he
did not know where he was going. Hebrews 11:8 (NIV)

输出会是这样的

JUNE 15\nWednesday\nBH 259: Trusting Jesus\nTRUSTING GOD\nText: Hebrews 11:7-12\n\nRBT: 1 Chron. 14-15;\nJohn 18:19-40\n

我尝试通过 fileinputstream 上的 read() 读取文件

in = new FileInputStream("2_jun.txt");
    out = new FileOutputStream("output.txt");

    int c;
    while((c = in.read()) != -1){
        out.write(c);
    }

但我无法比较行尾 因为我必须将 EOL 替换为“\n”

关于如何实现这一目标有什么建议吗?

最佳答案

如果您使用 ,您可能想使用 Files#lines .

它将返回 Stream<String>每个条目都是读取的文件的一行。

然后你可以按照你想要的方式处理它们。

String result;

try(Stream<String> lines = Files.lines(Paths.get("2_june.txt")){
    result = lines.map(x -> x + "\\n")
                  .collect(Collectors.joining());
}

关于java - 从文本文件获取输入并返回 json 字符串的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37772197/

相关文章:

javascript - 将值加载到 Selectize.js 中

javascript - 使用 javascript 的 FileReader 获取/设置文件编码

java - Android Wear OS 关闭 Wifi

java - 检查 JFrame 是否打开

java - android.view.InflateException : Binary XML file line #29: Error inflating class android. widget.Button

java - FileReader 和 BufferedReader 的作用——为什么要 wrapp FileReader?

java - 如何从java中的文本文件/文件夹中获取字数(不更改文件夹的读取顺序)

java - 当线程访问时,矩阵打印得不好

json - 在 bash 的特定 JSON 字段中查找最高值

c# - 更多 json c# 问题