Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Sending and Receiving File

  1. #1
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Sending and Receiving File

    Hi,
    Recently I have been trying to send and receive stuff over network. I have two computers and I was practicing with them. Sending a simple text was easy, but file was not easy.
    I kept trying but failed. So, I found an example on the Internet end tried to understand it.
    This is the receiver side of the code:
    import java.net.*;
    import java.io.*;
     
    public class FileClient{
      public static void main (String [] args ) throws IOException {
        int filesize=6022386; // filesize temporary hardcoded
     
        long start = System.currentTimeMillis();
        int bytesRead;
        int current = 0;
        // localhost for testing
        Socket sock = new Socket("127.0.0.1",13267);
        System.out.println("Connecting...");
     
        // receive file
        byte [] mybytearray  = new byte [filesize];
        InputStream is = sock.getInputStream();
        FileOutputStream fos = new FileOutputStream("source-copy.pdf");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = is.read(mybytearray,0,mybytearray.length);
        current = bytesRead;
     
        // thanks to A. Cádiz for the bug fix
        do {
           bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
           if(bytesRead >= 0) current += bytesRead;
        } while(bytesRead > -1);
     
        bos.write(mybytearray, 0 , current);
        bos.flush();
        long end = System.currentTimeMillis();
        System.out.println(end-start);
        bos.close();
        sock.close();
      }
    }

    They define int filesize=6022386; and use this as the array length, if I am not wrong. How do they know this?


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sending and Receiving File

    How do they know this?
    Maybe if they are on Windows, they right-clicked on the file and asked for the file's properties.

    It's possible to use a smaller array. In the read loop, read some bytes and write them to the output file.
    You do NOT have to read all the file's bytes before writing them to a file. That is poorly written code.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Sending and Receiving File

    Possibly (About being poorly written). I realized that it does not save anything into the file. So I put a sysout in every line. It gets stuck here:
    bytesRead = is.read(mybytearray,0,mybytearray.length);
    I waited for 5 minutes and the file was 1 kb.
    I think I lack knowledge about I/O. Because I do not even know how to fix this. The connecting part is very easy, but sending and receiving are not.

    So you suggest that I could read 32 bytes and write it, and do this in a loop.

    Although I felt a little lack of knowledge in myself, I'll have a try. And maybe re-read I/O topics. Thanks

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sending and Receiving File

    Do your first testing using the localhost address on one PC for easier debugging. Add lots of println statements to see what the code is doing.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Sending and Receiving File

    Thanks for the tips
    My procedure for testing network stuff goes like this: localhost, then my network ip, then the other computer. Never tried but assuming the right ip and port are provided, a code which is working on localhost can work on anywhere, I guess.

    Anyway, I just tried to write a method but I was clueless. So I am reading a book right now. I'll post here when I figure things out (Or if I can't).

    --- Update ---

    I managed to send files. But considering the examples I saw so far, I think although I was successful, it may not be always the case. Can you please tell me what else should I consider in this code? (Added throws Exception to simplify learning)

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
     
    public class Lol {
     
    	public void readClient() throws Exception{//Start server button	
    		ServerSocket serverSocket = new ServerSocket(clientPort);		
    		Socket mySocket = serverSocket.accept();
    		BufferedInputStream bis = new BufferedInputStream(mySocket.getInputStream());
    		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/As.exe"));
    		int read;
    		while((read = bis.read())> -1){
    			bos.write(read);
    		}
    		bos.flush();
    		bos.close();
    		bis.close();
    	}
     
    	public void sendData() throws Exception {
    		 Socket mySocket = new Socket(serverIp, Integer.parseInt(serverPort));	 
    		 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:/Default.exe"));
    		 BufferedOutputStream bos = new BufferedOutputStream(mySocket.getOutputStream());
    		 int read;
    		 while((read = bis.read())> -1){
    			 bos.write(read);
    		 }
    		 bis.close();
    		 bos.close();
     
    	}
    }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sending and Receiving File

    You could read and write more than one byte at a time using a byte array.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Sending and Receiving File

    Thanks Norm! That will be my next objective. But, can you spot any potential problems with that? Because the others were so long and some of them were so complex, I thought I might be missing some cases where this code will fail.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Sending and Receiving File

    Test the code and see what happens.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Jun 2011
    Posts
    94
    My Mood
    Amazed
    Thanks
    22
    Thanked 1 Time in 1 Post

    Default Re: Sending and Receiving File

    It is working flawless and it is weird for me to say, but I kinda wanted this to fail. Because comparing the examples and my code, I feel like they are testing the connection for something, but I neither see it in the code nor think anything about it.
    I have tried it with different computers of course. Wireless or cable network like it matters. I think I'll leave it as it is for now except for trying to write more than one byte at a time. Well, while I was writing this, I figured they might be testing the total bytes or something...
    Anyways, thanks.

Similar Threads

  1. [Asking] Sending and Receiving Data via Serial
    By ardisamudra in forum Java Networking
    Replies: 5
    Last Post: January 23rd, 2013, 06:24 AM
  2. [SOLVED] Sending xml file over a socket
    By Kakashi in forum Java Networking
    Replies: 2
    Last Post: March 9th, 2011, 09:41 AM
  3. Monitor the progress of sending a file to client
    By adumi in forum Java Theory & Questions
    Replies: 0
    Last Post: April 17th, 2010, 07:01 AM
  4. sending an email with pdf file everyday
    By pradeepptp in forum JavaServer Pages: JSP & JSTL
    Replies: 2
    Last Post: June 21st, 2009, 10:49 AM
  5. Sending and Receiving mail using J2ME without server
    By chals in forum Java ME (Mobile Edition)
    Replies: 5
    Last Post: June 2nd, 2009, 09:59 AM