blob: c08761ed0603292f62006572eecb384e0a18da8c [file] [log] [blame]
Nick Kralevich4fb25612009-06-17 16:03:22 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
19import android.util.Log;
20
21import java.io.Closeable;
22import java.io.EOFException;
23import java.io.FileInputStream;
24import java.io.FileOutputStream;
25import java.io.IOException;
26import java.io.InputStream;
27import java.io.OutputStream;
28
29/**
30 * A 4k block of random {@code byte}s.
31 */
32class RandomBlock {
33
34 private static final String TAG = "RandomBlock";
35 private static final int BLOCK_SIZE = 4096;
36 private byte[] block = new byte[BLOCK_SIZE];
37
38 private RandomBlock() { }
39
40 static RandomBlock fromFile(String filename) throws IOException {
41 Log.v(TAG, "reading from file " + filename);
42 InputStream stream = null;
43 try {
44 stream = new FileInputStream(filename);
45 return fromStream(stream);
46 } finally {
47 close(stream);
48 }
49 }
50
51 private static RandomBlock fromStream(InputStream in) throws IOException {
52 RandomBlock retval = new RandomBlock();
53 int total = 0;
54 while(total < BLOCK_SIZE) {
55 int result = in.read(retval.block, total, BLOCK_SIZE - total);
56 if (result == -1) {
57 throw new EOFException();
58 }
59 total += result;
60 }
61 return retval;
62 }
63
64 void toFile(String filename) throws IOException {
65 Log.v(TAG, "writing to file " + filename);
66 OutputStream out = null;
67 try {
68 // TODO: Investigate using RandomAccessFile
69 out = new FileOutputStream(filename);
70 toStream(out);
71 } finally {
72 close(out);
73 }
74 }
75
76 private void toStream(OutputStream out) throws IOException {
77 out.write(block);
78 }
79
80 private static void close(Closeable c) {
81 try {
82 if (c == null) {
83 return;
84 }
85 c.close();
86 } catch (IOException e) {
87 Log.w(TAG, "IOException thrown while closing Closeable", e);
88 }
89 }
90}