尝试将ObjectInputStream的输出保存到文件时发生IOException

问题描述:

我对使用流和Java文件的概念很陌生。尝试将ObjectInputStream的输出保存到文件时发生IOException

我写了一段代码,我有一个非常简单的服务器,它正在侦听传入文件。

然后我有一个处理传入文件的处理程序。

现在,这里是代码(剥离try/catch块的)

ObjectInputStream in; 

in = new ObjectInputStream(new BufferedInputStream(
     clientSocket.getInputStream())); 

File f = new File(fileName); 
int byteCount = in.readInt(); 
byte[] fileArray = (byte[]) in.readObject(); 
Files.write(f.toPath(), fileArray); 

总会有一个IOException当程序击中``字节[] fileArray =(字节[])in.readObject( ); line. And - to be sure, the INT byteCount`显示正确的字节数,文件名也是正确的......

堆栈跟踪看起来是这样的:

java.io.OptionalDataException 
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1304) 
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370) 
    at com.fileservice.util.ClientHandlerRunnable.run(ClientHandlerRunnable.java:85) 
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:262) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) 
    at java.lang.Thread.run(Thread.java:744) 

客户端发送的文件的代码:

Socket socket = new Socket(data.getIp(), data.getTcpPort()); 
    FileInputStream fis = null; 
    BufferedInputStream bis = null; 
    // OutputStream os = null; 

    // send file 
    File myFile = new File(data.getFileName()); 
    String test = myFile.getAbsolutePath(); 
    byte[] mybytearray = new byte[(int) myFile.length()]; 
    fis = new FileInputStream(myFile); 
    bis = new BufferedInputStream(fis); 
    bis.read(mybytearray, 0, mybytearray.length); 
    ObjectOutputStream os = new ObjectOutputStream(
      new BufferedOutputStream(socket.getOutputStream())); 
    os.flush(); 
    System.out.println("Sending " + data.getFileName() + "(" 
      + mybytearray.length + " bytes)"); 
    if (os != null) { 
     os.writeInt(mybytearray.length); 
     os.write(mybytearray, 0, mybytearray.length); 
     os.flush(); 
     System.out.println("Done."); 
    } 
    if (bis != null) { 
     bis.close(); 
    } 
    if (os != null) { 
     os.close(); 
    } 
    if (socket != null) { 
     socket.close(); 

    } 
+2

什么是异常的堆栈跟踪?客户端发送“文件”的代码是什么?发送/读取byteCount有什么意义,因为它根本不被使用? –

+0

添加了此信息。 – dziki

您正在发送原始字节,并且您正在读取一个对象。这是行不通的。如果您读取了一个对象,那么发件人必须写入一个对象(使用writeObject())。如果发件人写入字节,则必须读取字节(使用read())。

请注意,您的文件阅读部分也是错误的。 read()不保证它会读取您要求它读取的字节数。您必须使用循环来读取所有内容。或者您可以简单地使用Files.readAllBytes(),它会正确读取文件中的所有字节。