プロが教えるわが家の防犯対策術!

出力ストリームをバイト配列へ変換するには

いつもお世話になります。

BufferedOutpuStreamで取得したオブジェクトを(ByteArrayOutputStreamでインスタンス生成)、バイト配列へ変換するにはどのようにすればよいでしょうか。
ByteArrayOutputStreamだと、toByteArrayメソッドでバイト配列へ変換できるのですが、効率化を考慮し、BufferedOutputStreamへ出力するように
しているのですが、この場合だと取得したBufferedOutputStreamをバイト配列へ変換する方法が分からず困っています。

宜しくお願いします。

A 回答 (1件)

>ByteArrayOutputStreamでインスタンス生成



ByteBufferじゃ駄目なんですか?

 Bruce Eckel, "Thinking in Java (4th Edition)" (Prentice Hall, 2006)
によると、p.946~p.948に、次のようにあります。


The Java “new” I/O library, introduced in JDK 1.4 in the java.nio.* packages, has one goal: speed.
(中略)

The speed comes from using structures that are closer to the operating system’s way of performing I/O: channels and buffers.
(中略)

The only kind of buffer that communicates directly with a channel is a ByteBuffer?that is, a buffer that holds raw bytes.
(中略)

Three of the classes in the “old” I/O have been modified so that they produce a FileChannel: FileInputStream, FileOutputStream, and, for both reading and writing, RandomAccessFile.
Notice that these are the byte manipulation streams, in keeping with the low-level nature of nio.
The Reader and Writer character-mode classes do not produce channels, but the class java.nio.channels.Channels has utility methods to produce Readers and Writers from channels.

Here’s a simple example that exercises all three types of stream to produce channels that are writeable, read/writeable, and readable:

//: io/GetChannel.java
// Getting channels from streams
import java.nio.*;
import java.nio.channels.*;
import java.io.*;

public class GetChannel {
private static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
// Write a file:
FileChannel fc =
new FileOutputStream("data.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text ".getBytes()));
fc.close();
// Add to the end of the file:
fc =
new RandomAccessFile("data.txt", "rw").getChannel();
fc.position(fc.size()); // Move to the end
fc.write(ByteBuffer.wrap("Some more".getBytes()));
fc.close();
// Read the file:
fc = new FileInputStream("data.txt").getChannel();
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
fc.read(buff);
buff.flip();
while(buff.hasRemaining())
System.out.print((char)buff.get());
}
} /* Output:
Some text Some more
*///:~
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!