Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's very difficult to maintain a 1:1 mapping between a sequence of Java chars (which are effectively UTF-16) and bytes which could be anything depending on your file encoding. Even with UTF-8, the "obvious" mapping of 1 byte to 1 char only works for ASCII. Neither UTF-16 nor UTF-8 guarantees that a unicode character can be stored in a single machine <code>char</code> or <code>byte</code>.</p> <p>I would maintain my window into the file as a byte buffer, not a char buffer. Then to find line endings in the byte buffer, I'd encode the Java string <code>"\r\n"</code> (or possibly just <code>"\n"</code>) as a byte sequence using the same encoding as the file is in. I'd then use that byte sequence to search for line endings in the byte buffer. The position of a line ending in the buffer + the offset of the buffer from the start of the file maps exactly to the byte position in the file of the line ending.</p> <p>Appending lines is just a case of seeking to the end of the file and adding your new lines. Changing lines is more tricky. I think I would maintain a list or map of byte positions of changed lines and what the change is. When ready to write the changes:</p> <ol> <li>sort the list of changes by byte position</li> <li>read the original file up to the next change and write it to a temporary file.</li> <li>write the changed line to the temporary file.</li> <li>skip the changed line in the original file.</li> <li>go back to step 2 unless you have reached the end of the original file</li> <li>move the temp file over the original file. </li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload