How can Java write streams to an array?
In Java, data can be written to an array using either byte streams or character streams.
- Write to an array using byte stream.
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();
}
}
- Write to an array using character streams.
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();
}
}
Please note that in the above examples, you will need to obtain an input stream or a Reader object based on the specific situation. Additionally, remember to close the input stream or Reader object as well as the output stream or Writer object after finishing the operation.