我目前正在尝试从服务器响应中读取数据。我正在使用Socket连接到服务器,创建一个http GET请求,然后使用Buffered Reader读取数据。以下是代码看起来像压缩的内容:
Socket conn = new Socket(server, 80);
//Request made here
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String response;
while((response = inFromServer.readLine()) != null){
System.out.println(response);
}
我想读取数据,而不是字符串,作为字节数组,并将其写入文件。这怎么可能?非常感谢任何帮助,谢谢。
答案 0 :(得分:2)
您需要使用ByteArrayOutputStream
,执行以下代码:
Socket conn = new Socket(server, 80);
//Request made here
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int readBytes = -1;
while((readBytes = is.read(buffer)) > 1){
baos.write(buffer,0,readBytes);
}
byte[] responseArray = baos.toByteArray();
答案 1 :(得分:1)
一种方法是使用Apache commons-io IOUtils
byte[] bytes = IOUtils.toByteArray(inputstream);
答案 2 :(得分:0)
使用普通的java:
ByteArrayOutputStream output = new ByteArrayOutputStream();
try(InputStream stream = new FileInputStream("myFile")) {
byte[] buffer = new byte[2048];
int numRead;
while((numRead = stream.read(buffer)) != -1) {
output.write(buffer, 0, numRead);
}
} catch(IOException e) {
e.printStackTrace();
}
// and here your bytes
byte[] myDesiredBytes = output.toByteArray();
答案 3 :(得分:0)
如果您没有在项目中使用Apache commons-io库,我可以使用非常简单的方法来执行相同操作而不使用它。
/*
* Read bytes from inputStream and writes to OutputStream,
* later converts OutputStream to byte array in Java.
*/
public static byte[] toByteArrayUsingJava(InputStream is)
throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int reads = is.read();
while(reads != -1){
baos.write(reads);
reads = is.read();
}
return baos.toByteArray();
}