您好,我在使用 DataInputStream 的
当我通过 readLong()
方法时遇到了一些问题。DataOutputStream.writeLong()
它是正确的值,但是当它被发送时它比它应该的大很多,我把代码都放在一个可运行的语句中,这样程序就不会卡住
这是客户
socket = new Socket(ipAddress, Port);
bos = new BufferedOutputStream(socket.getOutputStream());
dos = new DataOutputStream(bos);
File f = new File("C:/Users/lukeLaptop/Downloads/RemoveWAT22.zip");
long length = f.length();
dos.writeLong(length);
String name = f.getName();
dos.writeUTF(name);
FileInputStream fis = new FileInputStream(f);
bis = new BufferedInputStream(fis);
int theByte = 0;
while ((theByte = bis.read()) != -1) {
bos.write(theByte);
}
bis.close();
dos.close();
服务器端
ServerSocket server = new ServerSocket(8080);
while (true) {
socket = server.accept();
System.out.println("Got a client !");
bis = new BufferedInputStream(socket.getInputStream());
dis = new DataInputStream(bis);
int filesCount = dis.readInt();
long fileLength = dis.readLong();
//String fileName = dis.readUTF();
File f = new File("C:/test/here/test.zip");
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
for (int j = 0; j < fileLength; j++) {
bos.write(bis.read());
}
bos.close();
dis.close();
编辑
如果有人可以帮助我编写代码,我将不胜感激并使用 writeUTF 发送名称,但我不知道发生了什么以及如何解决它
最佳答案
问题是方法writeUTF
。
javadoc说:
Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.
First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.
但是您使用自己的长度编码,它只需要字符串包含的字符数。它不使用字符串的编码长度。
如果使用 DataInputStream.readUTF()
,则不必使用自己的长度编码阅读你的字符串。
关于java - DataInputStream readLong() 得到错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21840587/