View Javadoc

1   /*
2    * Copyright (c) 2006-2007 Creative Sphere Limited.
3    * All rights reserved. This program and the accompanying materials
4    * are made available under the terms of the Eclipse Public License v1.0
5    * which accompanies this distribution, and is available at
6    * http://www.eclipse.org/legal/epl-v10.html
7    *
8    * Contributors:
9    *
10   *   Creative Sphere - initial API and implementation
11   *
12   */
13  package org.abstracthorizon.danube.webdav.fs;
14  
15  import java.io.File;
16  import java.io.IOException;
17  import java.io.OutputStream;
18  import java.io.RandomAccessFile;
19  
20  /**
21   * Output stream to a file based on {@link RandomAccessFile} with given length and initial offset.
22   *
23   * @author Daniel Sendula
24   */
25  public class RandomAccessFileRangeOutputStream extends OutputStream {
26  
27      /** Random access file reference */
28      protected RandomAccessFile raf;
29  
30      /** Length */
31      protected long len;
32  
33      /**
34       * Constructor
35       * @param file a file
36       * @param from initial offset
37       * @param len length
38       * @throws IOException thrown from {@link RandomAccessFile}
39       */
40      public RandomAccessFileRangeOutputStream(File file, long from, long len) throws IOException {
41          raf = new RandomAccessFile(file, "rw");
42          if (raf.length() < from + len) {
43              raf.setLength(from + len);
44          }
45          raf.skipBytes((int)from);
46          this.len = len;
47      }
48  
49      @Override
50      public void write(int i) throws IOException {
51          if (len != 0) {
52              raf.write(i);
53              len = len - 1;
54          }
55  
56      }
57  
58      @Override
59      public void write(byte[] buf, int from, int length) throws IOException {
60          if (length > len) {
61              length = (int)len;
62          }
63          raf.write(buf, from, length);
64          len = len - length;
65      }
66  
67      @Override
68      public void flush() throws IOException {
69      }
70  
71      @Override
72      public void close() throws IOException {
73          raf.close();
74      }
75  
76  }