2012-05-16 93 views
3

這應該很容易,但我現在無法理解它。我想通過套接字發送一些字節,像Java:從二進制文件讀取,通過套接字發送字節

Socket s = new Socket("localhost", TCP_SERVER_PORT); 
DataInputStream is = new DataInputStream(new BufferedInputStream(s.getInputStream())); 

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(s.getOutputStream())); 

for (int j=0; j<40; j++) { 
    dos.writeByte(0); 
} 

這工作,但現在我不想writeByte到的OutputStream,而是從二進制文件讀取,然後寫出來。我知道(?)我需要一個FileInputStream來讀取,我無法弄清楚構建整個事情。

有人可以幫我嗎?

+1

http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html介紹瞭如何從創建的FileInputStream一個文件名。 – dhblah

回答

3
public void transfer(final File f, final String host, final int port) throws IOException { 
    final Socket socket = new Socket(host, port); 
    final BufferedOutputStream outStream = new BufferedOutputStream(socket.getOutputStream()); 
    final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(f)); 
    final byte[] buffer = new byte[4096]; 
    for (int read = inStream.read(buffer); read >= 0; read = inStream.read(buffer)) 
     outStream.write(buffer, 0, read); 
    inStream.close(); 
    outStream.close(); 
}

這將是不正確的異常處理的簡單方法 - 在真實世界的設置,您就必須確保如果發生錯誤,關閉流。

您可能想要查看Channel類以及流的替代方法。例如,FileChannel實例提供了可能效率更高的transferTo(...)方法。

+0

謝謝,它的工作,真的幫助我,緩衝陣列的事情對我來說是新的。 – FWeigl

0

從輸入讀取一個字節和相同的字節寫入到輸出

或用字節的緩衝區這樣的:

inputStream fis=new fileInputStream(file); 
byte[] buff = new byte[1024]; 
int read; 
while((read=fis.read(buff))>=0){ 
    dos.write(buff,0,read); 
} 

注意,你不需要使用數據流進行這

2
 Socket s = new Socket("localhost", TCP_SERVER_PORT); 

     String fileName = "...."; 

使用的文件名

FileInputStream fis = new FileInputStream(fileName); 

創建一個FileInputStream文件對象

 FileInputStream fis = new FileInputStream(new File(fileName)); 

從文件

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(
     s.getOutputStream())); 

讀取字節後,從它字節讀取創建一個FileInputStream

int element; 
    while((element = fis.read()) !=1) 
    { 
     dos.write(element); 
    } 

或讀取緩存明智

byte[] byteBuffer = new byte[1024]; // buffer 

    while(fis.read(byteBuffer)!= -1) 
    { 
     dos.write(byteBuffer); 
    } 

    dos.close(); 
    fis.close();