0
您好我在将文件从客户端传输到服务器端时出现问题。从我最初的研究中,我发现DataInputStream可以用于我的传输。但不幸的是,使用DataInput/Output Stream传输的文件被损坏。文件大小保持不变,但是当我打开这些文件时,我看不到内容,文本中显示的是十六进制内容。
从一些互联网链接,我发现它可能是由于开放的套接字或流,但这并没有工作得很好。任何人都可以请帮我解决这个问题。我的文件在每次传输后都会损坏。客户端服务器文件传输
下面是我的代码:
Client Side Code
if (isConnected) {
File transferFile = new File(dir);
if (!transferFile.exists() || !transferFile.canRead()) {
System.out.println("error");
System.err.println();
}
OutputStream os = clientSocket.getOutputStream();
byte[] bytearray = new byte[(int) transferFile.length()];
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(transferFile.getName());
dos.writeLong(bytearray.length);
dos.write(bytearray, 0, bytearray.length);
dos.flush();
dos.close();
os.close();
Server Side Code
/* Test Code */
InputStream is = socket.getInputStream();
DataInputStream in = new DataInputStream(is);
String fileName =in.readUTF();
OutputStream output = new FileOutputStream(fileName);
long size = in.readLong();
byte[] buffer = new byte[1024];
int bytesRead;
while (size > 0 && (bytesRead = in.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1)
{
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
is.close();
output.close();
in.close();
socket.close();
Content of Input File:
This is a test file.
Contents of Output File:(Received by Server)
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000
上传前后添加一个小文件,以便我们可以看到错误。 – atk
确实让我马上去做 –
如果我遗漏了一些*完全*显而易见的东西,请原谅我,但'bytearray'在哪里给出了有意义的数据?看起来你正在写一个充满零值字节的数组。 – pathfinderelite