Search code examples
javasocketsfile-transfersocketchannelfilechannel

SocketChannel and FileChannel.transferFrom/To


I just learnt about the java nio package and channels and now, I tried to write a really simple file transfer program using channels. My aim was to get rid of all this bytewise reading stuff. As a first try, I wrote the following server code:

public class Server {
    public static void main(String args[]) throws FileNotFoundException, IOException {
        String destination = "D:\tmp\received"; 
        int port = 9999; 
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(9999)); 
        SocketChannel socketChannel = serverSocketChannel.accept(); 
        FileChannel fileChannel = new FileOutputStream(destination).getChannel();
        fileChannel.transferFrom(socketChannel, 0, 32); 
        socketChannel.close();
        serverSocketChannel.close();
    }
}

and the following client code:

public class Client {
    public static void main(String args[]) throws FileNotFoundException, IOException {
        String fileName = "D:\\dump\\file";
        InetSocketAddress serverAddress = new InetSocketAddress("localhost", 9999); 
        FileChannel fileChannel = new FileInputStream(fileName).getChannel();
        SocketChannel socketChannel = SocketChannel.open(serverAddress); 
        fileChannel.transferTo(0, fileChannel.size(), socketChannel); 
        socketChannel.close();
        fileChannel.close();
    }
}

to transfer a predefined 32-byte file over a predefined port without any kind of error handling and stuff.

This program compiles and runs without any errors, but at the end the destination file ("received") is not written.

Is it possible to transfer a file with this technique or did I misunderstood anything? Can you tell me what I did wrong in the above code? After some research, I have not found any solution yet, but just find code snippets that use this bytewise stuff (like: while(there is data) { read 32 byte and write them into file }).


Solution

  • "D:\tmp\received"
    

    Change these backslashes to forward slashes. This is either an illegal file name, which would have thrown an exception you should have noticed, or at least it is not a filename equal to the one you think you're writing.

    You also need to call these transfer methods in a loop until they have transferred everything you're expecting. That's why they have a return value. Check the Javadoc.