]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/engine/WriteBuffer.java
a8a92eef185168099287aa064e73fc53f81be622
[DictionaryPC.git] / src / com / hughes / android / dictionary / engine / WriteBuffer.java
1 // Copyright 2017 Reimar Döffinger
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package com.hughes.android.dictionary.engine;
16
17 import java.io.IOException;
18 import java.io.OutputStream;
19 import java.io.PipedInputStream;
20 import java.io.PipedOutputStream;
21
22 public class WriteBuffer extends PipedOutputStream {
23     static int BLOCK_SIZE = 1024 * 1024;
24     public WriteBuffer(OutputStream out, int size) {
25         assert size >= 2 * BLOCK_SIZE;
26         this.out = out;
27         try {
28             pipe = new PipedInputStream(this, size);
29             buffer = new byte[BLOCK_SIZE];
30             writeThread = new Thread(new Runnable() {
31                 public void run() {
32                     int read;
33                     try {
34                         while ((read = pipe.read(buffer)) > 0)
35                         {
36                             out.write(buffer, 0, read);
37                             out.flush();
38                         }
39                     } catch (IOException e) {
40                         System.out.println("Error writing to file " + e);
41                     }
42                     try {
43                         out.close();
44                     } catch (IOException e) {}
45                 }
46             });
47             writeThread.start();
48         } catch (IOException e) {}
49     }
50
51     public void close() throws IOException
52     {
53         super.close();
54         try {
55             writeThread.join();
56         } catch (InterruptedException e) {
57             System.out.println("Failed waiting for WriteBuffer thread " + e);
58         }
59     }
60
61     Thread writeThread;
62     OutputStream out;
63     PipedInputStream pipe;
64     byte buffer[];
65 }