Parsing and modifying a file in turn while saving EOL characters in Java

One long question :)

This is how I usually do it:

StringBuilder b = new StringBuilder();
BufferedReader r = new BufferedReader(new StringReader(s));
while ((String line = r.readLine()) != null)
    b.append(doSomethingToTheString(s) + "\n");

However, this replaces all new string characters in the file with a line feed, plus adds one to the end if there was none. I want to keep the EOL characters even if they are mixed like this:

Hello\r\n
World\n
This is\r
Messed up

What would be the most elegant / efficient way to do this?

+3
source share
3 answers

If you want to keep string terminators, use InputStreaminstead Reader. You will need to implement your own function readLine(), which searches for a standard character / newline pair and leaves it in the return value.

, , , Writer , System.getProperty("line.separator").

0

:)

BufferedReader.readLine() . , .

readLine() (, , ) , .

+3

, .

  • (, WeirdLine) , , byte [] .

    class WeirdLine { final String line; final byte[] term; }

  • (, WeirdLineReader), InputStream. readWeirdLine(), WeirdLine null,

  • WeirdLineReader . readWeirdLine(), (InputStream.read()), ,

    . read() -1, . readWeirdLine() , String new String(buffer[]).

    . findTerminator() , \r\n \n , . WeirdLine null, / .

    . , null

WeirdLine , .

This might be easiest to use ByteBuffer, rather than raw byte[]for the internal buffer.

You can probably adapt the code to BufferedReaderif that sounds intimidating.

0
source

Source: https://habr.com/ru/post/1769800/


All Articles