Hello,
I have just finished writing the code for my FTP application but according to my code, everything should work fine. But when I run my application, the file is not transfer to the server. Can someone please check where I am going wrong. I am sending the code as attachment.

Please Note: I only want the Client to send a file to the Server for the time being.

Thanks in advance ...

Attachments
package ignisftpv20;

import java.net.*;
import java.io.*;
import javax.swing.JOptionPane;


public class FTPClient implements Runnable {

ObjectInputStream input;
ObjectOutputStream output;
Socket s;


FileInputStream fis;
FileOutputStream fout;
File file;

public FTPClient(){
}


public FTPClient(int port){
    connectToServer(port);
    setIOStreams();
    new Thread( this ).start();
}



//connect to the server
public void connectToServer(int port){

   try{

    s  = new Socket ("127.0.0.1" , port);

    }catch(Exception e){e.printStackTrace();}
}


//set IO streams
public void setIOStreams(){

           try{
                
                output = new ObjectOutputStream(s.getOutputStream());
                output.flush(); // flush output buffer to send header information
                input = new ObjectInputStream(s.getInputStream());
                JOptionPane.showMessageDialog(null, "Client says: ... SetIO Streams");

            }catch(Exception e){e.printStackTrace();}
}


//send bytes to server
public void sendBytes(File f){
     

        try{

            JOptionPane.showMessageDialog(null, "Client says: File send ....");
            fis = new FileInputStream(f);
            JOptionPane.showMessageDialog(null, "Client says: The file name: " + f.getName());


            byte[] buffer = new byte[1024];
            int bytes = 0;

            while((bytes = fis.read(buffer))!=-1)
            {
                output.write(buffer,0,bytes);
            }
        }catch(Exception e){e.printStackTrace();}

}



//fos = FileOutputStream

//o = objIn.readObject();
//while (o instanceof Byte) {	 fos.write(((Byte) o).byteValue());
//o = objIn.readObject();
//}



////////////////////////////////////////////////////////////////////////////////
// CLIENT READS Incoming ....
// this starts in a background thread
public void run() {
    try {
        //reads incoming bytes forever
            while (true) {
                try
                {   //Testing only
                    String message = ( String ) input.readObject();
                    JOptionPane.showMessageDialog(null, message);
                } //end try
                catch(ClassNotFoundException e){e.printStackTrace();
                      //displayMessage( "\nOops, Alien object type received" );
                } // end catch
            }//end while
        }//end try
    catch( IOException ie ) { System.out.println( ie ); }
}// end of run
////////////////////////////////////////////////////////////////////////////////



}
package ignisftpv20;

import javax.swing.JFileChooser;
import java.io.*;

public class FTPClientInterface extends javax.swing.JFrame implements Runnable {



JFileChooser fileChooser = new JFileChooser();
File fileUpload;
FTPClient theFTPClient;



  public FTPClientInterface(FTPClient c) {
  initComponents();
  theFTPClient = c;
  }



    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnBrowse = new javax.swing.JButton();
        btnSend = new javax.swing.JButton();
        btnConnect = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("FTP Client");

        btnBrowse.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btnBrowse.setText("Browse");
        btnBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBrowseActionPerformed(evt);
            }
        });

        btnSend.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btnSend.setText("Send File");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        btnConnect.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        btnConnect.setText("Connect");
        btnConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConnectActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(66, 66, 66)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSend)
                    .addComponent(btnBrowse)
                    .addComponent(btnConnect))
                .addContainerGap(80, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnBrowse, btnConnect, btnSend});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(56, 56, 56)
                .addComponent(btnConnect)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnBrowse)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(63, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnBrowse, btnConnect, btnSend});

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-237)/2, (screenSize.height-268)/2, 237, 268);
    }// </editor-fold>//GEN-END:initComponents



//browse
    private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseActionPerformed
        int flag = fileChooser.showOpenDialog(FTPClientInterface.this);

        if (flag == JFileChooser.APPROVE_OPTION) {
            fileUpload = fileChooser.getSelectedFile();
            //theFTPClient.sendBytes(fileUpload);
        }



}//GEN-LAST:event_btnBrowseActionPerformed



//connect
    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed
            new Thread( this ).start();
    }//GEN-LAST:event_btnConnectActionPerformed


    
    
//send file
    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
        theFTPClient.sendBytes(fileUpload);
    }//GEN-LAST:event_btnSendActionPerformed


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FTPClient c = new FTPClient();
                new FTPClientInterface(c).setVisible(true);

            }
        });
    }


public void run(){

        try{
           new FTPClient(5555);
        }//end try
        catch(Exception e){e.printStackTrace();}
}



    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBrowse;
    private javax.swing.JButton btnConnect;
    private javax.swing.JButton btnSend;
    // End of variables declaration//GEN-END:variables

}
package ignisftpv20;

import java.net.*;
import java.io.*;
import javax.swing.JOptionPane;
public class FTPServer {

ObjectInputStream input;
ObjectOutputStream output;
Socket soc ;




public FTPServer(){
waitForConnection();
}

public void waitForConnection(){
            try{
                ServerSocket ss = new ServerSocket(5555);

                    while(true){
                        soc = ss.accept();
                        JOptionPane.showMessageDialog(null, "Server says: OK ... I got a connection!");
                        setIOStreams();
                        System.out.println("Connected from: "+ soc.getInetAddress().getHostName()+"..." );
                        new FTPServerReceiver( this, soc );
                    }

            }catch(Exception e){ e.printStackTrace();}

}


public void setIOStreams(){
           try{
                output = new ObjectOutputStream(soc.getOutputStream());
                output.flush(); // flush output buffer to send header information
                input = new ObjectInputStream(soc.getInputStream());
                JOptionPane.showMessageDialog(null, "Server says: SetIO Streams Ready...");

            }catch(Exception e){e.printStackTrace();}


}

}
package ignisftpv20;

public class FTPServerInterface extends javax.swing.JFrame implements Runnable {


    public FTPServerInterface() {
        initComponents();
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Server Interface");

        jButton1.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jButton1.setText("Launch Server");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(74, 74, 74)
                .addComponent(jButton1)
                .addContainerGap(90, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(48, 48, 48)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(62, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
            new Thread( this ).start();

    }//GEN-LAST:event_jButton1ActionPerformed


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FTPServerInterface().setVisible(true);

            }
        });
    }



    public void run(){

        try{
            new FTPServer();
        }//end try
        catch(Exception e){e.printStackTrace();}
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    // End of variables declaration//GEN-END:variables

}
package ignisftpv20;

import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;

public class FTPServerReceiver implements Runnable{


    FTPServer ftpServer;
    Socket thesocket;
    Byte bt;
    ObjectInputStream input;
    FileOutputStream fout;

    String directoryName = "C:/Documents and Settings/My User/Desktop/Complete Download";


    public FTPServerReceiver(FTPServer ftpServer, Socket s){

        this.ftpServer = ftpServer;
        this.thesocket = s;
        new Thread( this ).start();
    }

//read and write file
    public void run(){

        try{
            while(true){
            JOptionPane.showMessageDialog(null, "Server Receiver says: Incoming in progress ...");
            input = new ObjectInputStream(thesocket.getInputStream());
            byte[] buffer = new byte[1024];
            int bytes = 0;
            
            input.read(buffer,0,bytes);

            File f = new File(directoryName,"file1");
            fout = new FileOutputStream(f);
            fout.write(input.read(buffer,0,bytes));

            }

        }catch(Exception e){e.printStackTrace();}

        //JOptionPane.showMessageDialog(null, "Reception completed ...");

    }
}

In FTPServerReceiver you just have one input.read(), and it's not in a loop. Have you tried sending the buffer to System.out immediately after the read so you can see what's coming in?
Where exactly is it failing? - try to scatter some System.out.println statements around so you can see how far the client and server are getting, eg insidethe read /write loops

Hello,
I have changed the code, still not working, can you please check if its the right way to write to a file. Thanks a lot.

//read and write file
    public void run(){
 
        try{
            while(true){
                JOptionPane.showMessageDialog(null, "Server Receiver says: Incoming in progress ...");
                byte[] buffer = new byte[1024];
                int bytes = 0;
                input = new ObjectInputStream(thesocket.getInputStream());
                 //input.read(buffer,0,bytes);
                File f = new File(directoryName,"filetest");
                fout = new FileOutputStream(f);
                //fout.write(input.read(buffer,0,bytes));

                //new changes
                while(done){
                    if( (input.read(buffer,0,bytes)) == 0){
                        done = false;
                    }
                    else{
                        System.out.println(input.read(buffer,0,bytes));
                         fout.write(input.read(buffer,0,bytes));
                    }
                 }

            }

        }catch(Exception e){e.printStackTrace();}

        //JOptionPane.showMessageDialog(null, "Reception completed ...");

    }

Some quick comments:
"done" works backwards! Logically valid, but confusing. Can't see where it's declared or initialised.
EOF is signalled by -1, not 0. I don't know if EOF will ever get sent on a socket connection (unless the client closes the connection?).
The System.out reads the input stream, so it gets read twice in the loop! You should just print the buffer.
In writing the file you write the return value from the read. That's just the byte count. You need to write the buffer to the file.
You don't close the file.
Did you compile this; try to run it?

Sorry ... I declared done at the top as a boolean value and set to true.

boolean done = true

Yes .. I compiled it,no errors, the program run ... but its seems to work but the program does not write the file.

And I can't see the output of this piece of code:

System.out.println(input.read(buffer,0,bytes));

I changed the EOF to -1, still nothing. I tried to write the buffer ... still nothing. Please help me on this part , thanks in advance.

This article has been dead for over six months. Start a new discussion instead.