Vikesh Vikesh - 5 months ago 7
JSON Question

Program which takes input from a text file and returns a json string

Here is an example of my text file

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)


And output would be something like

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


I tried reading file by read() on fileinputstream

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

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


but i am not able to compare End of line
since i have to just replace EOL with "\n"

any suggestions as to how this can be achieved ?

Answer

If you're using , you may want to use Files#lines.

It'll return a Stream<String> with each entry being a line of the file read.

Then you process them however you want.

String result;

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