View Javadoc

1   /*
2    ******************************************************************************
3    * Copyright (c) 2005 Chris Rose and AIMedia All rights reserved.
4    * DocumentOutputStream and the accompanying materials are made available under
5    * the terms of the Common Public License v1.0 which accompanies this
6    * distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html
7    * Contributors: Chris Rose
8    ******************************************************************************/
9   package com.aimedia.ui;
10  
11  import java.io.*;
12  
13  import javax.swing.text.*;
14  
15  /***
16   * An output stream for writing to a <code>Document</code>.
17   * 
18   * @author Chris Rose
19   */
20  public class DocumentOutputStream extends OutputStream {
21  
22     private Document document;
23  
24     /*** Creates a new instance of DocumentOutputStream */
25     public DocumentOutputStream(Document doc) {
26        if (doc == null) {
27           throw new NullPointerException(
28                 "Cannot pass a null document to this constructor");
29        }
30        this.document = doc;
31     }
32  
33     public void write(byte[] buf, int offset, int length) throws IOException {
34        try {
35           document.insertString(document.getLength(), new String(buf, offset, length),
36                 null);
37        } catch (BadLocationException ble) {
38           throw new IOException("Document append failed : " + ble);
39        }
40     }
41  
42     public void write(int b) throws IOException {
43        try {
44           document.insertString(document.getLength(),
45                 new String(new byte[] { (byte) b }), null);
46        } catch (BadLocationException ble) {
47           throw new IOException("Document append failed : " + ble);
48        }
49     }
50  }