简体   繁体   中英

Reading newline char in java

I am appending and streaming a bunch of files and I want to trim the header line after the first file. On windows the following java code adds a blank line and I see garbled chars in notepad++. Any fixes/suggestions? Thank you.

    private int updateHeader(byte[] buffer) throws UnsupportedEncodingException {
      if (first) {
        return buffer.length;
      }
      String s, s2;
      s = new String(buffer, "UTF-8");
      int k = s.indexOf(System.getProperty("line.separator"), 0);
      s2 = s.substring(k + 1);
      byte[] buffer2 = s2.getBytes("UTF-8");
      System.arraycopy(buffer2, 0, buffer, 0, buffer2.length);
      return buffer2.length;
   }

My guess is that you should do something like:

...
String separator = System.getProperty("line.separator");
int k = s.indexOf(separator, 0);
s2 = s.substring(k + separator.length());
s2 = s2.trim();
...

Windows line separators are more than 1 character long (CR + LF) vs. Unix which is LF based on this . Also, this might be tricky if you move files across platforms.

EDIT I'm not sure what you're seeing since I don't quite have the files, but you could try trimming the substring as well if you see funky characters. Are you sure the files are of the right encoding and that you're reading them properly?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM