【发布时间】:2014-04-28 13:15:06
【问题描述】:
我正在尝试将文件发送到我的服务器。我让它处理小于 100mb 的文件。否则我的堆用完了。所以我重做了它,但不能真正让它工作。除了读取我卡在 bis.read(buffer) 中的最后一个数据之外,我还开始工作,因为它不知道文件何时结束。所以我尝试发送每个段的长度,以便 bufferedInputStream 知道何时停止读取。
知道有什么问题吗?
发件人代码:
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[2048];
Integer bytesRead = 0;
BufferedOutputStream bos = new BufferedOutputStream(clientSocket.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(fis);
while ((bytesRead = bis.read(buffer)) > 0) {
objectOutStream.writeObject(bytesRead);
bos.write(buffer, 0, bytesRead);
}
System.out.println("Sucess sending file");
接收方(服务器):
fileName = request.getFileName();
int size = (int) request.getSize();
BufferedInputStream bis = new BufferedInputStream(clientSocket.getInputStream());
FileOutputStream fos = new FileOutputStream(fileName);
int totalBytesReceived = 0;
int blockSize = 0;
while (totalBytesReceived < size) {
Object o = ois.readObject();
if (!(o instanceof Integer)) {
System.out.println("Something is wrong");
}
blockSize = (Integer) o;
buffer = new byte[blockSize];
bis.read(buffer);
totalBytesReceived += blockSize;
fos.write(buffer, 0, blockSize);
}
System.out.println("File succes");
【问题讨论】: