gpt4 book ai didi

java 。从 BufferedInputStream 读取并写入 FileOutputStream

转载 作者:行者123 更新时间:2023-12-03 01:32:12 29 4
gpt4 key购买 nike

我正在尝试用java编写客户端和服务器端。服务器端正常(在多个客户端上检查)。

所以,问题出在客户端。我为 bytearray 分配内存,从 BufferedInputStream 读取并写入该 bytearray。然后从bytearray写入FileOutputStream。一切正常,但 bytearray 的可用空间被 NULL 填充,因此接收到的文件不正确(例如图像)。

我发现了该问题的 2 个决定:

  1. 读取bytearray直到文件末尾(但我不知道文件末尾在哪里)
  2. BufferedInputStream读取到FileInputStream,但不起作用:

我实际上需要接收 header 和文件。将 header 输出到控制台并将文件写入光盘。

完整来源

public class SClient {
private static int bufferSize = 8192;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter the address:");
BufferedReader bufferRead = new BufferedReader
(new InputStreamReader(System.in));

try {
String address = bufferRead.readLine();
System.out.println("Enter the extention of receiving file:");
String fileExt = bufferRead.readLine();
// TODO code application logic here
Socket socket = new Socket(address,4040);
BufferedInputStream bis = new BufferedInputStream
(socket.getInputStream());

BufferedOutputStream bout = new BufferedOutputStream
(socket.getOutputStream());
System.out.println("Enter the request:");
String message = bufferRead.readLine();// GET /index.html HTTP/1.0

System.out.println("Header read");
if(message!=null){
bout.write(message.getBytes());
}
FileOutputStream fout = new FileOutputStream("out"+fileExt);
String s1 = "\r\n\r\n";
bout.write(s1.getBytes());
bout.flush();
System.out.println("Header sent");

byte[] res = new byte[bufferSize];
int got;
while((got = bis.read(res))!=-1){
fout.write(res,0,got);
}
fout.close();
bout.flush();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

服务器端源码:

    String endLine = "\r\n";
File f = new File(fileName);
FileInputStream fstream;
fstream = new FileInputStream(f);
response = "HTTP/1.0 200 OK" + endLine;
header = "Content-type: "+ contentType + endLine + "Content-length: " + f.length() + endLine + endLine;
bout.write(response.getBytes());
bout.write(header.getBytes());
while(fstream.read(buffer) != -1) {
bout.write(buffer);
}
System.out.println("Message sent");
bout.flush();
socket.close();

最佳答案

您必须记住读入缓冲区的字节数,并且只能将这些字节写回。像这样:

int got;
while ((got = bis.read(res)) != -1) {

fout.write(res, 0, got);
}

关于 java 。从 BufferedInputStream 读取并写入 FileOutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18779654/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com