Java:从二进制文件中读取,通过套接字发送字节

3
这应该很简单,但我现在无法理解它。我想通过套接字发送一些字节,例如:
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);
}

这个方法是可行的,但现在我不想向OutputStream写入字节,而是要从二进制文件中读取内容,然后写出来。我知道需要使用FileInputStream进行读取,但我无法构建好整个过程。

有人可以帮助我吗?


1
http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html 解释了如何从文件名创建FileInputStream。 - dhblah
3个回答

4
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();
}

如果没有适当的异常处理,这将是一种天真的方法 - 在现实世界中,如果发生错误,您必须确保关闭流。

您可能还想查看通道类作为流的替代方案。例如,FileChannel实例提供了transferTo(...)方法,可能更加高效。


谢谢,它有效并真的帮了我很大的忙,缓冲数组这个东西对我来说是新的。 - fweigl

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

        String fileName = "....";

使用文件名创建一个FileInputStream。
    FileInputStream fis = new FileInputStream(fileName);

创建一个FileInputStream文件对象。
        FileInputStream fis = new FileInputStream(new File(fileName));

从文件中读取

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

逐字节从中读取

    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();

0

从输入读取一个字节并将相同的字节写入输出

或者使用字节缓冲器像这样:

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

请注意,您无需使用DataStreams来完成此操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接