Take the 2-minute tour ×
public boolean FileToByteArray(DatagramSocket socket, InetAddress dst_addr, int dst_port) throws Exception{
        File file = new File("input.txt");
        InputStream is = new FileInputStream(file);
        long length = file.length();
        int offset = 0, n = 0;
        DatagramPacket out_pkt = null;

            while (offset < bytes.length && (n = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += n;
                out_pkt = new DatagramPacket(bytes, pkt_size, dst_addr, dst_port);
                System.out.println("*****************" + packetCount);

            String s = new String(bytes);
            System.out.println(s + " " + s.length()) ;
            return true;


hi all, I am dealing with an assignment that needs me to send large text file through UDP. I am able to read the 10000 byte but when i set pkt_size to 1000, it only delivery 1000 byte which is 1KB of data over. How do i break large file to small packets to send?

share|improve this question
What does "when i set pkt_size to 1000, it only delivery 1000 byte which is 1KB of data over" mean? What did you expect exactly? What's the question here? –  EJP Nov 12 '12 at 9:08
Sorry, what i meant was how do a break down a 1MB text file into packets of 1000 bytes each and send to receiver where the receiver will write it into another file. The end result is input text file must be equal to output text file –  Lawrey Nov 12 '12 at 9:22
@EJP, I also don't understand the question. Lawrey, you need to read chunks of 1000 bytes from file continiously, then create packet for each chunk in loop and send it. –  Nikolay Kuznetsov Nov 12 '12 at 10:57
You can refer to code for reading chunks in here stackoverflow.com/questions/9588348/java-read-file-by-chunks –  Nikolay Kuznetsov Nov 12 '12 at 10:57

Your Answer



Browse other questions tagged or ask your own question.