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

时间:2016-06-12 08:31:42

标签: 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);
    }

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

有关如何实现这一目标的任何建议?

1 个答案:

答案 0 :(得分:2)

如果您使用的是,则可能需要使用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());
}