2012-12-15 43 views
0

這是我的第一個問題,所以我希望我能正確寫入它。Java套接字,獲取圖像文件,但它不會打開

我想通過Java套接字發送一個byte []數組,該數組包含一個圖像。

下面是發送文件的代碼:

public void WriteBytes(FileInputStream dis) throws IOException{ 
    //bufferEscritura.writeInt(dis.available()); --- readInt() doesnt work correctly 
    Write(String.valueOf((int)dis.available()) + "\r\n"); 
    byte[] buffer = new byte[1024]; 
    int bytes = 0; 
    while((bytes = dis.read(buffer)) != -1){ 
     Write(buffer, bytes); 
    } 
    System.out.println("Photo send!"); 
} 
public void Write(byte[] buffer, int bytes) throws IOException { 
    bufferEscritura.write(buffer, 0, bytes); 
} 
public void Write(String contenido) throws IOException { 
    bufferEscritura.writeBytes(contenido); 
} 

我的形象:

URL url = this.getClass().getResource("fuegos_artificiales.png"); 
FileInputStream dis = new FileInputStream(url.getPath()); 
sockManager.WriteBytes(dis); 

我的代碼來獲取圖像文件:

public byte[] ReadBytes() throws IOException{ 
DataInputStream dis = new DataInputStream(mySocket.getInputStream()); 
int size = Integer.parseInt(Read()); 
System.out.println("Recived size: "+ size); 
byte[] buffer = new byte[size]; 
System.out.println("We are going to read!"); 
dis.readFully(buffer); 
System.out.println("Photo received!"); 
return buffer; 

}

public String Leer() throws IOException { 
    return (bufferLectura.readLine()); 
} 

並創建映像文件:

byte[] array = tcpCliente.getSocket().LeerBytes(); 
FileOutputStream fos = new FileOutputStream("porfavor.png"); 
try { 
    fos.write(array); 
} 
finally { 
    fos.close(); 
} 

創建映像文件,但是當我嘗試用畫圖打開它,例如它說,它不能打開它,因爲它已損壞...... 我還嘗試用記事本打開兩張圖像(原始圖像和新圖像),並且它們內部具有相同的數據!

我不知道發生了什麼......

我希望你能幫助我。

謝謝!

+0

在notepand中打開文件不是一個好的比較方法。在發送之前和接收之後比較字節數組的長度。 – Booyaches

+0

是的,我比較它,sendind字節之前,我寫的文件的長度和讀取之前,我創建一個字節[]緩衝區與接收的值的大小相同。而且,生成的文件與原始文件具有相同的大小,所以我不會發生什麼...... – user1906398

回答

1
  1. 請勿使用available()作爲文件長度的度量。事實並非如此。 Javadoc對此有一個特別的警告。

  2. 使用DataOutputStream.writeInt()寫入長度,並使用DataInputStream.readInt()讀取它,並使用相同的流讀取圖像數據。不要在同一個套接字上使用多個流。

同樣在此:

URL url = this.getClass().getResource("fuegos_artificiales.png"); 
FileInputStream dis = new FileInputStream(url.getPath()); 

第二行應該是:

InputStream in = URL.openConnection.getInputStream(); 

課程資源是不是一個文件。

+0

您可以使用'URLConnection.getContentLength()'獲取圖像數據的大小。 – VGR

相關問題