2015-05-18 190 views
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 
+0

上传前后添加一个小文件,以便我们可以看到错误。 – atk

+0

确实让我马上去做 –

+1

如果我遗漏了一些*完全*显而易见的东西,请原谅我,但'bytearray'在哪里给出了有意义的数据?看起来你正在写一个充满零值字节的数组。 – pathfinderelite

回答

0

你从来没有真正写整个文件。你只写了一个与文件大小相同的零值字节数组(你的bytearray变量)。服务器接收字节数组,并将其填充为零值字节,并将其保存到文件中。因此,服务器保存的文件与原始文件具有相同的大小,但是充满了零(NULL),在大多数文本编辑器中它们将显示为垃圾。您需要先将文件内容写入bytearray

相关问题