1 /*******************************************************************************
2 * Copyright (c) 2010 Association for Decentralized Information Management in
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.databoard.util;
14 import java.io.EOFException;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.OutputStream;
19 import java.nio.ByteBuffer;
20 import java.nio.channels.Channels;
21 import java.nio.channels.ReadableByteChannel;
22 import java.nio.channels.WritableByteChannel;
23 import java.nio.charset.Charset;
25 import org.simantics.databoard.util.binary.BinaryFile;
26 import org.simantics.databoard.util.binary.BinaryMemory;
28 public class StreamUtil {
30 public static String readString(InputStream is, Charset cs) throws IOException
32 byte[] data = readFully(is);
33 return new String(data, cs);
36 public static String readString(File file, Charset cs) throws IOException
38 byte[] data = readFully(file);
39 return new String(data, cs);
42 public static byte[] readFully(InputStream is) throws IOException
44 BinaryMemory mem = new BinaryMemory( 0 );
46 byte[] result = new byte[ (int) mem.length() ];
48 mem.readFully(result);
52 public static byte[] readFully(File file) throws IOException
54 BinaryFile b = new BinaryFile(file);
56 byte[] bytes = new byte[ (int) b.length() ];
65 public static void read(InputStream is, ByteBuffer buf, int bytes)
68 while (bytes>0 & buf.hasRemaining()) {
69 int n = is.read(buf.array(), buf.position(), bytes);
70 if (n < 0) throw new EOFException();
71 buf.position( buf.position() + n );
76 public static void readFully(InputStream is, ByteBuffer buf)
79 while (buf.hasRemaining()) {
80 int n = is.read(buf.array(), buf.position(), buf.remaining());
81 if (n < 0) throw new EOFException();
82 buf.position( buf.position() + n );
86 public static void readFully(InputStream is, byte[] b)
89 readFully(is, b, 0, b.length);
92 public static void readFully(InputStream is, byte[] b, int off, int len)
96 int n = is.read(b, off, len);
97 if (n < 0) throw new EOFException();
103 public static void writeFully(byte[] data, File dst) throws IOException {
104 BinaryFile out = new BinaryFile(dst);
113 public static void copyStream(InputStream is, OutputStream out)
116 ReadableByteChannel ic = Channels.newChannel(is);
117 WritableByteChannel oc = Channels.newChannel(out);
119 ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
120 while (ic.read(buffer) != -1) {
126 while (buffer.hasRemaining()) {