2012-12-15 45 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

相关问题