0
我對使用流和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();
}
什麼是異常的堆棧跟蹤?客戶端發送「文件」的代碼是什麼?發送/讀取byteCount有什麼意義,因爲它根本不被使用? –
添加了此信息。 – dziki