Debian Codegraph @

demo/src/main/java/NewlineOutputStream.java

raw
1 /*
2 * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
3 *
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Distribution License v. 1.0, which is available at
6 * http://www.eclipse.org/org/documents/edl-v10.php.
7 *
8 * SPDX-License-Identifier: BSD-3-Clause
9 */
10
11 import java.io.*;
12
13 /**
14 * Convert the various newline conventions to the local platform's
15 * newline convention. <p>
16 *
17 * This stream can be used with the Message.writeTo method to
18 * generate a message that uses the local plaform's line terminator
19 * for the purpose of (e.g.) saving the message to a local file.
20 */
21 public class NewlineOutputStream extends FilterOutputStream {
22 private int lastb = -1;
23 private static byte[] newline;
24
25 public NewlineOutputStream(OutputStream os) {
26 super(os);
27 if (newline == null) {
28 String s = System.lineSeparator();
29 if (s == null || s.length() <= 0)
30 s = "\n";
31 try {
32 newline = s.getBytes("iso-8859-1"); // really us-ascii
33 } catch (UnsupportedEncodingException ex) {
34 // should never happen
35 newline = new byte[] { (byte)'\n' };
36 }
37 }
38 }
39
40 public void write(int b) throws IOException {
41 if (b == '\r') {
42 out.write(newline);
43 } else if (b == '\n') {
44 if (lastb != '\r')
45 out.write(newline);
46 } else {
47 out.write(b);
48 }
49 lastb = b;
50 }
51
52 public void write(byte b[]) throws IOException {
53 write(b, 0, b.length);
54 }
55
56 public void write(byte b[], int off, int len) throws IOException {
57 for (int i = 0 ; i < len ; i++) {
58 write(b[off + i]);
59 }
60 }
61 }