javaでストリームを配列に書き込む方法は何ですか?
Javaでは、データを配列に書き込む際には、バイトストリームまたは文字ストリームを使用することができます。
- 配列にバイトストリームを書き込む。
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Main {
public static void main(String[] args) throws IOException {
InputStream input = ...; // 获取输入流
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) != -1) {
output.write(buffer, 0, length);
}
byte[] data = output.toByteArray();
// 使用数据数组进行后续操作
input.close();
output.close();
}
}
- 配列に文字ストリームを使用して書き込む:
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;
public class Main {
public static void main(String[] args) throws IOException {
Reader reader = ...; // 获取Reader对象
CharArrayWriter writer = new CharArrayWriter();
char[] buffer = new char[1024];
int length;
while ((length = reader.read(buffer)) != -1) {
writer.write(buffer, 0, length);
}
char[] data = writer.toCharArray();
// 使用数据数组进行后续操作
reader.close();
writer.close();
}
}
注意,上記の例では、具体的な状況に応じて入力ストリームやリーダーオブジェクトを取得する必要があります。また、操作が完了したら、入力ストリームやリーダーオブジェクト、そして出力ストリームやライターオブジェクトを閉じることを忘れないでください。