Click here to Skip to main content
15,884,808 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I made a file transfer project that sends any type of files but there is a problem that the file sent is not saved , I don't know what is wrong with my code ?
the file chooser opens correctly and the selection is fine but there is something wrong in the receiver cant figure it out ...
This is the File Transfer code :

public class File_transferer {

private JFrame frame;
private JTextField textField;
String ip;
    int port;
    File selFile;
    Path path;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                File_transferer window = new File_transferer();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public File_transferer() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 449, 219);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JLabel lblPleaseSelectA = new JLabel("Please select a file to be sent to the Server");
    lblPleaseSelectA.setBounds(10, 39, 227, 14);
    frame.getContentPane().add(lblPleaseSelectA);

    JButton btnBrowse = new JButton("Browse");
    btnBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser fc = new JFileChooser();
            //filter-show only .txt files
            FileNameExtensionFilter txtfilter = new FileNameExtensionFilter("","zip","pdf","mp3","3GP","7Z","AAC", 
                    "ACE","AIF","ARJ","ASF","AVI","BIN","BZ2 ","EXE","GZ","GZIP",
                    "IMG","ISO ","LZH","M4A","M4V","MKV","MOV","MP3 ","MP4"," MPA",
                    "MPE"," MPEG"," MPG","MSI"," MSU","OGG","OGV","PDF","PLJ","PPS",
                    "PPT ","QT","R0*","R1* ","RA","RAR","RM","SEA","SIT","SITX ",
                    "TAR","TIF","TIFF","WAV","WMA","WMV","Z","ZIP","png","jepg","gif",
                    "flv","doc","docx","ppt","xlsx","java","jar","flv","bmp","dip");


            //apply the filter to file chooser
            fc.setFileFilter(txtfilter);
            fc.setDialogTitle("Otvori txt file");
            //disable the ability to show files of all extensions
            fc.setAcceptAllFileFilterUsed(false);
            //create file chooser via jFrame
            fc.showOpenDialog(frame);
            //get selected file
            selFile = fc.getSelectedFile();
            path = Paths.get(selFile.toString());
            String asdf = selFile.toString();
            //display chosen file on jLabel5
            textField.setText(path.getFileName().toString());
        }
    });
    btnBrowse.setBounds(335, 35, 89, 23);
    frame.getContentPane().add(btnBrowse);

    textField = new JTextField();
    textField.setBounds(10, 115, 414, 20);
    frame.getContentPane().add(textField);
    textField.setColumns(10);

    JLabel lblFileSourceRoot = new JLabel("File source root:");
    lblFileSourceRoot.setBounds(10, 90, 95, 14);
    frame.getContentPane().add(lblFileSourceRoot);

    JButton btnSend = new JButton("Send");
    btnSend.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            Socket s=null;
            BufferedReader get=null;
            PrintWriter put=null;


                try {
                    s=new ClientInitiator().socket;
                    s=new Socket(ip,4000);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    OutputStream filename= new FileOutputStream(path.toString());
                } catch (FileNotFoundException e3) {
                    // TODO Auto-generated catch block
                    e3.printStackTrace();
                }
                try {
                    get=new BufferedReader(new InputStreamReader(s.getInputStream()));
                } catch (IOException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
                try {
                    put=new PrintWriter(s.getOutputStream(),true);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }        


            try {
                InputStreamReader get2=new InputStreamReader(s.getInputStream());
            } catch (IOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            String u,f = null;
            DataInputStream dis=new DataInputStream(System.in);
            try {
                f=dis.readLine();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            put.println(f);
            File f1=new File("c:\\output");
            FileOutputStream fs = null;
            try {
                fs = new FileOutputStream(f1);
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            BufferedInputStream d = null;
            try {
                d = new BufferedInputStream(s.getInputStream());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            BufferedOutputStream outStream = null;
            try {
                outStream = new BufferedOutputStream(new FileOutputStream(f1));
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            byte buffer[] = new byte[60000];
            int read;
            try {
                while((read = d.read(buffer))!=-1)
                {
                    outStream.write(buffer, 0, read);
                    outStream.flush();
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                while((u=get.readLine())!=null)
                 { 
                   byte jj[]=u.getBytes();
                   fs.write(jj);
                }
            } catch (IOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            } 
            try {
                fs.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            System.out.println("File received");
            try {
                s.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            }


    });
    btnSend.setBounds(168, 146, 89, 23);
    frame.getContentPane().add(btnSend);
}


And this is the File Receiver code that receives the file :

public class File_Recever {

   public static void main(String[] args) throws IOException {
       int filesize=6022386; // filesize temporary hardcoded

       long start = System.currentTimeMillis();
       int bytesRead;
       int current = 0;
       InputStream path;

       // create socket
       ServerSocket servsock = new ServerSocket(4000);
       while (true) {
         System.out.println("Waiting...");

         Socket sock = servsock.accept();
         System.out.println("Accepted connection : " + sock);

      // receive file
           byte [] mybytearray  = new byte [filesize];
           InputStream is = sock.getInputStream();
           InputStream path1 = null;
           FileOutputStream fos = new FileOutputStream("C:\\Users\\Public\\Downloads\\"+path1); // destination path and name of file
           BufferedOutputStream bos = new BufferedOutputStream(fos);
           bytesRead = is.read(mybytearray,0,mybytearray.length);
           current = bytesRead;


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



Thanks in advance .
Posted
Comments
[no name] 27-Apr-13 14:24pm    
"something wrong" is not a very helpful description of any kind of a problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900