Java.IO file transfer

Hi all,
I have been trying to transfer the file from one server to another using java code. Using the api in the java.IO and the code from the following site http://www.roseindia.net/java/example/java/io/CopyDirectory.shtml
First i shared the folder to be transfered, then at the receiving end, i map the network drive.. Using the code as in the site, i can transfer the file over.
But i found that if the connection break in the mapping of the network drive, the code cannot resume the file transfer from where it left behind.
Actually, my requiremnts is to able to transfer the file and able to resume from where it stop when the connection break and not to overwrite any files.. and it able to check the sending server if there is any new files added to the folder, if yes then it will transfer over the receiving server.
Thanks
cheng

Using ... the code from the following site http://www.roseindia.net/java/example/java/io/CopyDirectory.shtml
That was your first mistake. That site is a notorious source of complete rubbish. In this case, unusually, the code looks not too bad apart from not calling mkdirs() as well as mkdir().
But i found that if the connection break in the mapping of the network drive, the code cannot resume the file transfer from where it left behind.Correct. It doesn't do that. So you need to modify it to do so. If it finds that the target file exists and has a non-zero length, it needs to open it for append and skip to that offset in the source file before starting the copy loop. If it finds that the target file exists and has the same length as the source file and the same date it can skip the file completely. That should cover both your requirements.

Similar Messages

  • Data loss in the secure file transfer using java

    Hi,
    My java Appllication uses the sftp(secure file transfer protocol) for file transferring. when the load is high like 150 GB , data loss occuring for some files especially last chunk of data is missing.
    Core file transfer code
    while (true)
    int read = bis.read(buffer); //Reading bytes into the byte array (buffer) from network stream (bis).
    if (read==-1) {
    break; //Break the loop, if there are no more bytes available in the InputStream.
    bos.write(buffer,0,read); //Writing the same number of bytes what we read into buffer byte array into OutputStream
    complete.update(buffer,0,read); //Giving the same number of bytes what we read above to the checksum calculation.
    bytesSoFar += read; //Incrementing the bytes that we have read from the source.
    //if the bytes transferred are equal to the source file size
    If (bytesSoFar == fileInfo.getFileSize().intValue())
    // Calculate the file checksum.
    // Update DbAuditLog with checksum and no. of bytes read
    else
    // Update DbAuditLog with no. of bytes read
    bos.flush();
    Please help , why the data loss is happening when the big size files transfer
    Note:
    1.150 gb not a single file multiple files.
    2.SFTP no java specific API, So connection is happening through java .io.sockect connection

    so, if you are not getting any exceptions, yet the data is incorrect, it sounds like you are having actual network issues. i'd start looking at things like the actual network cards in the computer as well other equipment involved in the transfer. since you are not getting exceptions, the network stack obviously thinks nothing was lost over the wire, so either the actual hardware has issues, or the network stack, or the issue is on the sending end. the last possibility is that the client is somehow munging the data it is sending. do you control the client code? if so, i'd start checking the client side code for bugs (and/or post it here).
    also, i'm assuming that all of the variables included in your original code are thread local (you aren't sharing any of those buffers/streams/etc between multiple threads).

  • Java Code to transfer a file through FTP

    I am writing a java code to transfer a file from local machine to a server on another machine.
    While uploading i am encountering with an exception which is showing as
    java.net.ConnectException: Connection refused: connect
    The file is getting transferred sucessfully if i am transferring it through command prompt instead of java code.
    Please help me out.

    Actually the code i have written is working fine when the two machines are local.
    But it is not working when the two syastems are connected through avantail.
    Then it is giving an exception
    java.net.ConnectException: Connection refused: connect
    while uploading

  • JAVA file transfer

    Hello,
    I am currently working on an application that is to create a multipart response to the client.
    The first part of this response is to send an xml descriptor file, and the second part of this response is to send a content object (audio or image).
    The xml descriptor file needs to be generated dynamically according to the http headers received from the client and then sent to the client. How should I go about doing this? Just write everything I would in the xml file in a String, convert the String into bytes [] and write it to the response output stream? or create an actual temporary file on the hard disk, and then send that file to the output stream? I am new to JAVA so, really do not know the best approach to take.
    Note: I am prohibited due to some company policies to generate XML files using JAVAX or similar technologies.
    Any help would be appreciated.
    Thanks,
    Saurabh

    so r u saying that i can implement File transfer using only client APIs?
    but cudnt find it.. so plz explain a little. http://www.catb.org/~esr/faqs/smart-questions.html
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Thyrsus Enterprises
    Copyright © 2001,2006 Eric S. Raymond, Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal — in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse “its” with “it's”, “loose” with “lose”, or “discrete” with “discreet”. Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes. Worse: writing like a l33t script kiddie hax0r is the absolute kiss of death and guarantees you will receive nothing but stony silence (or, at best, a heaping helping of scorn and sarcasm) in return.

  • Pdf file transfer using ftp in java

    Hi,
    I am tried to get a pdf file from ftp. I am using the following code. This code works fine with .txt files but not with .pdf files. The pdf file generated is empty.
    import java.awt.Desktop;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import org.apache.commons.net.ftp.FTPClient;
    public class FTPConn {
           public static void main(String[] args) throws FileNotFoundException {
            FTPClient f = new FTPClient();
            try {
                f.connect(ip);
                f.login("username", "password");
                File dir = new File("dir");
                dir.mkdir();
                File myFile = new File(dir, "myfile19.pdf");
                myFile.createNewFile();
                FileOutputStream fout = new FileOutputStream(myFile);
                String content= fout.toString();
                boolean success = f.retrieveFile("/location on ftp/ftp.pdf", fout);
                System.out.println("Content :"+content);
                if (success) {
                    fout.flush();
                    fout.close();
                } else {
                    System.out.println("Reterive failure");
                Desktop d = Desktop.getDesktop();
                d.open(myFile);
            }catch(Exception e){
                e.printStackTrace();

    Hi,
    I am tried to get a pdf file from ftp. I am using the following code. This code works fine with .txt files but not with .pdf files. The pdf file generated is empty.
    import java.awt.Desktop;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import org.apache.commons.net.ftp.FTPClient;
    public class FTPConn {
           public static void main(String[] args) throws FileNotFoundException {
            FTPClient f = new FTPClient();
            try {
                f.connect(ip);
                f.login("username", "password");
                File dir = new File("dir");
                dir.mkdir();
                File myFile = new File(dir, "myfile19.pdf");
                myFile.createNewFile();
                FileOutputStream fout = new FileOutputStream(myFile);
                String content= fout.toString();
                boolean success = f.retrieveFile("/location on ftp/ftp.pdf", fout);
                System.out.println("Content :"+content);
                if (success) {
                    fout.flush();
                    fout.close();
                } else {
                    System.out.println("Reterive failure");
                Desktop d = Desktop.getDesktop();
                d.open(myFile);
            }catch(Exception e){
                e.printStackTrace();

  • File transfer, read write through sockets in client server programming java

    Hello All, need help again.
    I am trying to create a Client server program, where, the Client first sends a file to Server, on accepting the file, the server generates another file(probably xml), send it to the client as a response, the client read the response xml, parse it and display some data. now I am successful sending the file to the server, but could not figure out how the server can create and send a xml file and send it to the client as response, please help. below are my codes for client and server
    Client side
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class XMLSocketC
         public static void main(String[] args) throws IOException
              //Establish a connection to socket
              Socket toServer = null;
              String host = "127.0.0.1";     
              int port = 4444;
              try
                   toServer = new Socket(host, port);
                   } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to host.");
                System.exit(1);
              //Send file over Socket
            //===========================================================
            BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // File to be send over the socket.
              File file = new File("c:/xampp/htdocs/thesis/sensorList.php");
              // Checking for the file to be sent.
              if (!file.exists())
                   System.out.println("File doesn't exist");
                   System.exit(0);
              try
                   // InputStream to read the file
                   fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee)
                   System.out.println("Problem, kunne ikke lage fil");
              try
                   InetAddress adressen = InetAddress.getByName(host);
                   try
                        System.out.println("Establishing Socket Connection");
                        // Opening Socket
                        Socket s = new Socket(adressen, port);
                        System.out.println("Socket is clear and available.....");
                        // OutputStream to socket
                        out = new BufferedOutputStream(s.getOutputStream());
                        byte[] buffer = new byte[1024];
                        int numRead;
                        //Checking if bytes available to read to the buffer.
                        while( (numRead = fileIn.read(buffer)) >= 0)
                             // Writes bytes to Output Stream from 0 to total number of bytes
                             out.write(buffer, 0, numRead);
                        // Flush - send file
                        out.flush();
                        // close OutputStream
                        out.close();
                        // close InputStrean
                        fileIn.close();
                   }catch (IOException e)
              }catch(UnknownHostException e)
                   System.err.println(e);
            //===========================================================
            //Retrieve data from Socket.
              //BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
              DataInputStream in = new DataInputStream(new BufferedInputStream(toServer.getInputStream()));
              //String fromServer;
            //Read from the server and prints.
              //Receive text from server
              FileWriter fr = null;
              String frn = "xxx_response.xml";
              try {
                   fr = new FileWriter(frn);
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              try{
                   String line = in.readUTF();                    //.readLine();
                   System.out.println("Text received :" + line);
                   fr.write(line);
              } catch (IOException e){
                   System.out.println("Read failed");
                   System.exit(1);
            in.close();
            toServer.close();
    public class XMLSocketS
          public static void main(String[] args) throws IOException
              //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4444);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
              while (true)
                        try
                             clientLink = serverSocket.accept();
                           System.out.println("Server accepts");
                             BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             // close the link to client
                             clientLink.close();                         
                             // close InputStream
                             inn.close();                         
                             // flush
                             ut.flush();                         
                             // close OutputStream
                             ut.close();     
                             //Sending response to client     
                             //============================================================
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
    }

    SERVER
    import java.net.*;
    import java.io.*;
    public class XMLSocketS
          public static void main(String[] args) throws IOException
                   //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4545);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
                  try
                             clientLink = serverSocket.accept();
                         System.out.println("Server accepts the client request.....");
                         BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             ut.flush();                         
                             //Sending response to client     
                             //============================================================
                             BufferedInputStream ftoC = null;
                             BufferedOutputStream outtoC = null;
                             // File to be send over the socket.
                             File file = new File("c:/xampp/htdocs/thesis/user_registration_response.xml");
                             try
                                  // InputStream to read the file
                                   ftoC = new BufferedInputStream(new FileInputStream(file));
                             }catch(IOException eee)
                             {System.out.println("Problem reading file");}
                             // OutputStream to socket
                             outtoC = new BufferedOutputStream(clientLink.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int noRead;
                             //Checking if bytes available to read to the buffer.
                             while( (noRead = ftoC.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  outtoC.write(buffer, 0, noRead);
                             outtoC.flush();
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
          }CLIENT SIDE
    import java.io.*;
    import java.net.*;
    public class XMLSocketC
              @SuppressWarnings("deprecation")
              public static void main(String[] args)
                   // Server: "localhost" here. And port to connect is 4545.
                   String host = "127.0.0.1";          
                   int port = 4545;
                   BufferedInputStream fileIn = null;
                   BufferedOutputStream out = null;
                   // File to be send over the socket.
                   File file = new File("c:/xampp/htdocs/thesis/sensorList.xml");
                   try
                        // InputStream to read the file
                        fileIn = new BufferedInputStream(new FileInputStream(file));
                   }catch(IOException eee)
                   {System.out.println("Problem");}
                   try
                             System.out.println("Establishing Socket Connection");
                             // Opening Socket
                             Socket clientSocket = new Socket(host, port);
                             System.out.println("Socket is clear and available.....");
                             // OutputStream to socket
                             out = new BufferedOutputStream(clientSocket.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int numRead;
                             //Checking if bytes available to read to the buffer.
                             while( (numRead = fileIn.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  out.write(buffer, 0, numRead);
                             // Flush - send file
                             out.flush();
                             //=======================================
                             DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                             BufferedWriter outf = new BufferedWriter(new FileWriter("c:/xampp/htdocs/received_from_server.txt",true));
                             String str;
                             while(!(str = in.readLine()).equals("EOF")) {     
                                  System.out.println("client : Read line -> <" + str + ">");
                                  outf.write(str);//Write out a string to the file
                                  outf.newLine();//write a new line to the file (for better format)
                                  outf.flush();
                             //=======================================
                             // close OutputStream
                             out.close();
                             // close InputStrean
                             fileIn.close();
                             // close Socket
                             clientSocket.close();
                        }catch (IOException e)
                        {System.out.println("Exception.");}
         Could you please point where am I doing the stupid mistake, client to server is working properly, but the opposite direction is not.
    Thanks

  • Java.io.EOFException in Object file transfer

    Greetings,
    I am having a problem sending a file across a network. At one point it was working, however I am not sure where along the way it became broken.
    Stack Trace:
    java.io.EOFException
    at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Sour
    ce)
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at WBServer.unpackVectors(WBServer.java:283)
    at fileListener.run(WBServer.java:374)
        public void getWBContent(String hid) throws java.rmi.RemoteException //<- Send all object vectors and relevant integers...
            setPageNum(pageCount-1);
            HID=hid;
            packVectors(null);
            new Thread() {
                public void run(){
                   try{javax.swing.SwingUtilities.invokeLater(
                   new Runnable(){
                       public void run(){
                            try{ //Yes...
                                java.net.Socket s = new java.net.Socket(HID, 1113); //<- Make a network port
                                java.io.BufferedWriter sos = new java.io.BufferedWriter(new java.io.OutputStreamWriter(s.getOutputStream())); //<-Open a stream
                                sos.write("vectordata.dat"); //<-Send the name of the file
                                sos.close(); //<- Close the stream
                                s.close(); //<- Close the port
                                String anchor = getClass().getResource("WBServer.class").getPath();
                                java.net.Socket ns = new java.net.Socket(HID, 1113); //<- Open a new port to the same place
                                java.io.FileInputStream fio = new java.io.FileInputStream(anchor.substring(0, anchor.lastIndexOf('/')+1)+"vectordata.dat"); //<- Open the file to stream
                                //java.io.DataInputStream dia = new java.io.DataInputStream(fio); //<- Open the stream to read
                                java.io.BufferedInputStream bia = new java.io.BufferedInputStream(fio);
                                java.io.BufferedOutputStream boa = new java.io.BufferedOutputStream(ns.getOutputStream());//<- Open the data stream for the port
                                int read=0; //<- Byte Read Counter
                                byte[] fbuffer = new byte[1024]; //<- Byte Read Buffer
                                boolean EOF=false;
                                while(!EOF){ //<- Until we reach the end of the stream...
                                    try{read=bia.read(fbuffer);
                                    boa.write(fbuffer, 0, read);} //<- ...send the number of bytes stored in the buffer at the time.
                                    catch(java.io.EOFException e){ EOF=true;}
                                boa.flush(); //<- Make sure the stream is cleared
                                boa.close(); //<- Close the port's stream
                                bia.close(); //<- Close the reading stream
                                fio.close(); //<- Close the file's stream
                                ns.close(); //<- Close the port...
                            catch(Exception e)
                            {SimpleFormatter sf = new SimpleFormatter();
                             LogRecord tempLog = new LogRecord(Level.WARNING, "File Send Error: "+e.toString());
                             sf.format(tempLog);
                             logFile.publish(tempLog);}
                    catch(Exception e)
                    {SimpleFormatter sf = new SimpleFormatter();
                     LogRecord tempLog = new LogRecord(Level.WARNING, "Error running getWBContent() send file thread: "+e.toString());
                     sf.format(tempLog);
                     logFile.publish(tempLog);}
                }}.start();
        public void packVectors(String filePath) {   //This function writes all the objects in memory to a file for transport.
            String anchor = getClass().getResource("WBServer.class").getPath();
            if(filePath==null){filePath=anchor.substring(0, anchor.lastIndexOf('/')+1)+"data/vectordata.dat";}
            System.out.println("From packVectors(): "+filePath);
            java.io.File ovFile = new java.io.File(filePath); //Setup out data file
            try{if(!ovFile.exists()){ovFile.createNewFile();}else{ovFile.delete(); ovFile.createNewFile();} //If it's not there...make one. If it is, delete it and make a new one.
            java.io.ObjectOutputStream oojStream = new java.io.ObjectOutputStream(new java.io.FileOutputStream(ovFile)); //Ready the writer for writingness.
            oojStream.writeObject(PageHolder); //Pages to file...
            oojStream.writeObject(ImgPage); //Images for the Pages to file...
            oojStream.writeObject(WBStack); //Current object stack to file...
            oojStream.writeInt(objCount); //Current object count to file...
            oojStream.writeInt(pageCount); //Current page count to file...
            oojStream.writeInt(pageCount-1); //Current page number to file...
            oojStream.flush(); //<-Commit final write operations...
            oojStream.close();} //<- Close the file...
            catch(Exception e)
            {SimpleFormatter s = new SimpleFormatter();
             LogRecord tempLog = new LogRecord(Level.WARNING, "Persistence save error: "+e.toString());
             s.format(tempLog);
             e.printStackTrace();
             logFile.publish(tempLog);}
        public void unpackVectors(String filePath) {   //This function reads objects from a file that was previously written by packVectors().
            String anchor = getClass().getResource("WBServer.class").getPath();
            if(filePath==null){filePath=anchor.substring(0, anchor.lastIndexOf('/')+1)+"data/vectordata.dat";}
            System.out.println("From unpackVectors(): "+filePath);
            java.io.File ivFile = new java.io.File(filePath); //Setup the file to read from.
            try{if(!ivFile.exists()){ //If the file doesn't exist, we're screwed...
                SimpleFormatter s = new SimpleFormatter();
                LogRecord tempLog = new LogRecord(Level.WARNING, "Persistence load error: File vectordata.dat does not exist!");
                s.format(tempLog);
                logFile.publish(tempLog);
            }else{
                java.io.ObjectInputStream iojStream = new java.io.ObjectInputStream(new java.io.FileInputStream(ivFile)); //Ready the reader for readingness...
                PageHolder = (java.util.Vector)iojStream.readObject(); //Pages from file...
                ImgPage = (java.util.Vector)iojStream.readObject(); //images for Pages from file...
                WBStack = (java.util.Vector)iojStream.readObject(); //Current object stack from file...
                objCount = iojStream.readInt(); //Current object count from file...
                pageCount = iojStream.readInt(); //Current number of pages from file...
                pageNum = iojStream.readInt();//iojStream.readInt(); //Current page number from file...
                iojStream.close();}} //Close the file...
            catch(Exception e)// We screwed up somewhere.....
            {SimpleFormatter s = new SimpleFormatter();
             LogRecord tempLog = new LogRecord(Level.WARNING, "Persistence load error: "+e.toString());
             s.format(tempLog);
             e.printStackTrace();
             logFile.publish(tempLog);}
    class fileListener extends Thread {
        public fileListener(WBServer wb) //<-Constructor
            try{ms = new java.net.ServerSocket(1113);} //<- Listener socket
            catch(Exception e){e.toString();}
            server = wb; //<- Referencial variable back to the server
        public fileListener(WBServer wb, int port) //<- Constructor with port
            try{ms = new java.net.ServerSocket(port);} //<- Listener socket
            catch(Exception e){e.toString();}
            server = wb; //<- Referencial variable back to the server
        public void run() {
            String filepath; //<- Holder for file path operations...
            while(!disconnect) {
                try{java.net.Socket cs = ms.accept(); //<- Accept incoming request.
                server.fileStat = 1;
                java.io.BufferedReader str = new java.io.BufferedReader(new java.io.InputStreamReader(cs.getInputStream())); //<- Open communications with client
                String checkStr = str.readLine(); //<- Grab the file name from the client
                System.out.println(checkStr);
                String anchor = getClass().getResource("fileListener.class").getPath();
                if(checkStr.equalsIgnoreCase("vectordata.dat"))
                {filepath=anchor.substring(0, anchor.lastIndexOf('/')+1)+"data/"+checkStr;}
                else{filepath=anchor.substring(0, anchor.lastIndexOf('/')+1)+"scans/"+checkStr;}
                System.out.println(filepath);
                str.close(); //<- Close communications with client
                cs.close(); //<- Close socket
                //System.out.println("Recieved File Name: "+filepath);//Debugging
                java.io.File inFile = new java.io.File(filepath); //<- Make a file in memory on the host computer with the specified name.
                inFile.createNewFile(); //<- Create an empty file of that name within the local file system
                java.net.Socket ds = ms.accept(); //<- Accept incoming request
                java.io.FileOutputStream fos = new java.io.FileOutputStream(inFile); //<- Open file stream for writing...
                java.io.BufferedInputStream bis = new java.io.BufferedInputStream(ds.getInputStream()); //<- Open communications with client for data/
                byte[] fbuffer = new byte[1024]; //<- Byte read buffer
                int read=0; //<- Byte read counter
                server.fileStat = 2;
                while((read=bis.read(fbuffer))!=-1){ //<-Until we reach the end of the stream...
                    fos.write(fbuffer, 0, read); System.out.print(read+":");}// <- ...write the buffer to the file.
                fos.flush(); //<- Clear the file stream
                fos.close(); //<- Close the file stream
                bis.close(); //<- Close the data stream from the client
                if(checkStr.equalsIgnoreCase("vectordata.dat"))
                {server.fileStat = 3; // ...otherwise, we show loading...
                 server.unpackVectors(null);
                 server.sendRefresh(true);
                 server.fileStat=0;}
                else //If it's the sych data, unpack it and load the data
                {server.fileStat = 3; // ...otherwise, we show loading...
                 server.passImage(inFile); //<-Load the file into the image vector...
                 server.sendRefresh(true); //<- Ensure that the client updates properly
                 server.fileStat=0;}
                ds.close(); //<- Close the client socket
                catch(Exception e){e.toString();}
            //System.out.println("Listener Shutdown");//Debugging
            try{ms.close();} catch(Exception e){e.toString();} //<- Close the listening socket
        public boolean disconnect = false; //<- Flag for killing the "file server" prematurely
        private static WBServer server; //<- Referencial variable to the whiteboard server
        private java.net.ServerSocket ms; //<- Listener socket
    }I'm stumped as to where it is going wrong. I know that packVectors() and unpackVectors() both work, as they are used in a local save function. I suspect the problem lies between the getWBContent(String hid) and the fileListener class, but I am not certain where. Any help would be appreciated.

    First, you are expecting read(buffer,offset,count) to throw an EOFException. It doesn't, it returns -1 at EOF.
    Second, you are using a Writer to write binary data (resulting from serialization). This will corrupt it. Use an OutputStream.
    Third, what I really don't get is why would you (i) write local data to a file and (ii) start a new thread to (iii) read it back and (iv) send it over not one but two sockets, when you could just return the data as the result of the remote method without the file, the thread, or the Sockets.
    And in any case this sort of thing is most definitely not what SwingtUtilites.invokeLater() is for. (What it is for is updating Swing components and ensuring it all happens in the Swing thread, being the only correct way to write Swing code as Swing is not thread-safe by design.) If your server has a Swing GUI, which doesn't seem likely, it will stall for the duration of all this I/O. If it doesn't, why start the Swing thread at all?
    Just define a serializable object that contains all the data you are passing to writeObject()/writeInt() and return it as the result of the remote method.
    You will save yourself a lot of latency and code in the process, and you could reduce all this to about six lines of code, something like:
    return new WBContent(
    PageHolder, //Pages to file...
    ImgPage, //Images for the Pages to file...
    WBStack, //Current object stack to file...
    objCount, //Current object count to file...
    pageCount, //Current page count to file...
    pageCount-1 //Current page number to file...
    ); where WBContent is a serializable class with the appropriate members and constructor, and is the return type of getWBContent().

  • How to increase the speed of network file transfer

    hi ,
    In my application i want to use the file from one system to another system.
    i am using stream reader to get the file over the network , its working fine for small file,
    but i want to access file size exceed 10 MB then i faced the problem. Its get very slow the file transfer over the network.
    so i am try to use java NIO for transfer file,
    Using NIO , While i am make server and client both are same system then the file tranfer is 10MB file in 10 seconds , but i am making server and client are different machine then its take so long to transfer file ie (10 MB file in 3 minutes).
    I want to reduce the time . If any chance to reduced the file transfer time then please suggest me.
    my code is
    Server Code :
    public class NioServer implements Runnable {
      // The host:port combination to listen on
      private InetAddress hostAddress;
      private int port;
      // The channel on which we'll accept connections
      private ServerSocketChannel serverChannel;
      // The selector we'll be monitoring
      private Selector selector;
      // The buffer into which we'll read data when it's available
      private ByteBuffer readBuffer = ByteBuffer.allocate(10000);
      private EchoWorker worker;
      // A list of PendingChange instances
      private List pendingChanges = new LinkedList();
      // Maps a SocketChannel to a list of ByteBuffer instances
      private Map pendingData = new HashMap();
      public NioServer(InetAddress hostAddress, int port, EchoWorker worker) throws IOException {
        this.hostAddress = hostAddress;
        this.port = port;
        this.selector = this.initSelector();
        this.worker = worker;
      public void send(SocketChannel socket, byte[] data) {
        System.out.println("Server Send ");
        synchronized (this.pendingChanges) {
          // Indicate we want the interest ops set changed
          this.pendingChanges.add(new ChangeRequest(socket, ChangeRequest.CHANGEOPS, SelectionKey.OP_WRITE));
          // And queue the data we want written
          synchronized (this.pendingData) {
            List queue = (List) this.pendingData.get(socket);
            if (queue == null) {
              queue = new ArrayList();
              this.pendingData.put(socket, queue);
            queue.add(ByteBuffer.wrap(data));
        // Finally, wake up our selecting thread so it can make the required changes
        this.selector.wakeup();
      public void run() {
        while (true) {
          try {
            // Process any pending changes
            synchronized (this.pendingChanges) {
              Iterator changes = this.pendingChanges.iterator();
              while (changes.hasNext()) {
                ChangeRequest change = (ChangeRequest) changes.next();
                switch (change.type) {
                case ChangeRequest.CHANGEOPS:
                  SelectionKey key = change.socket.keyFor(this.selector);
                  key.interestOps(change.ops);
              this.pendingChanges.clear();
            // Wait for an event one of the registered channels
            this.selector.select();
            // Iterate over the set of keys for which events are available
            Iterator selectedKeys = this.selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
              SelectionKey key = (SelectionKey) selectedKeys.next();
              selectedKeys.remove();
              if (!key.isValid()) {
                continue;
              // Check what event is available and deal with it
              if (key.isAcceptable()) {
                this.accept(key);
              } else if (key.isReadable()) {
                this.read(key);
              } else if (key.isWritable()) {
                this.write(key);
          } catch (Exception e) {
            e.printStackTrace();
      private void accept(SelectionKey key) throws IOException {
        System.out.println("Server Accept ");
        // For an accept to be pending the channel must be a server socket channel.
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        // Accept the connection and make it non-blocking
        SocketChannel socketChannel = serverSocketChannel.accept();
        Socket socket = socketChannel.socket();
        socketChannel.configureBlocking(false);
        // Register the new SocketChannel with our Selector, indicating
        // we'd like to be notified when there's data waiting to be read
        socketChannel.register(this.selector, SelectionKey.OP_READ);
      private void read(SelectionKey key) throws IOException {
        System.out.println("server Read : ");
        SocketChannel socketChannel = (SocketChannel) key.channel();
        // Clear out our read buffer so it's ready for new data
        readBuffer.clear();
    //    readFully( readBuffer , socketChannel ) ;
        // Attempt to read off the channel
        int numRead;
        try {
          numRead = socketChannel.read(readBuffer);
        } catch (IOException e) {
          // The remote forcibly closed the connection, cancel
          // the selection key and close the channel.
          key.cancel();
          socketChannel.close();
          return;
        if (numRead == -1) {
          // Remote entity shut the socket down cleanly. Do the
          // same from our end and cancel the channel.
          key.channel().close();
          key.cancel();
          return;
        // Hand the data off to our worker thread
        this.worker.processData(this, socketChannel, this.readBuffer.array(), numRead);
      private void write(SelectionKey key) throws IOException {
        System.out.println("Server Write ");
        SocketChannel socketChannel = (SocketChannel) key.channel();
        synchronized (this.pendingData) {
          List queue = (List) this.pendingData.get(socketChannel);
          // Write until there's not more data ...
          while (!queue.isEmpty()) {
            ByteBuffer buf = (ByteBuffer) queue.get(0);
            socketChannel.write(buf);
            if (buf.remaining() > 0) {
              System.out.println( "buf.remaining() " + buf.remaining() ) ;
              // ... or the socket's buffer fills up
              break;
            queue.remove(0);
          if (queue.isEmpty()) {
            // We wrote away all data, so we're no longer interested
            // in writing on this socket. Switch back to waiting for
            // data.
            key.interestOps(SelectionKey.OP_READ);
      private Selector initSelector() throws IOException {
        // Create a new selector
        Selector socketSelector = SelectorProvider.provider().openSelector();
        // Create a new non-blocking server socket channel
        this.serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        // Bind the server socket to the specified address and port
        InetSocketAddress isa = new InetSocketAddress(this.hostAddress, this.port);
        serverChannel.socket().bind(isa);
        // Register the server socket channel, indicating an interest in
        // accepting new connections
        serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);
        return socketSelector;
      private static void readFully(ByteBuffer buf, SocketChannel socket) throws IOException
        int len = buf.limit() - buf.position();
        while (len > 0)
          len -= socket.read(buf);
      public static void main(String[] args) {
        try {
          EchoWorker worker = new EchoWorker();
          new Thread(worker).start();
          new Thread(new NioServer(null, 9090, worker)).start();
        } catch (IOException e) {
          e.printStackTrace();
    }Client Code :
    public class NioClient implements Runnable {
      // The host:port combination to connect to
      private InetAddress hostAddress;
      private int port;
      // The selector we'll be monitoring
      private Selector selector;
      // The buffer into which we'll read data when it's available
      private ByteBuffer readBuffer = ByteBuffer.allocate( 10596 ) ;
      // A list of PendingChange instances
      private List pendingChanges = new LinkedList();
      // Maps a SocketChannel to a list of ByteBuffer instances
      private Map pendingData = new HashMap();
      private byte[] bufferByteA = null ;
      // Maps a SocketChannel to a RspHandler
      private Map rspHandlers = Collections.synchronizedMap(new HashMap());
      public NioClient(InetAddress hostAddress, int port) throws IOException {
        this.hostAddress = hostAddress;
        this.port = port;
        this.selector = this.initSelector();
      public void send(byte[] data, RspHandler handler) throws IOException {
        // Start a new connection
        SocketChannel socket = this.initiateConnection();
        // Register the response handler
        this.rspHandlers.put(socket, handler);
        // And queue the data we want written
        synchronized (this.pendingData) {
          List queue = (List) this.pendingData.get(socket);
          if (queue == null) {
            queue = new ArrayList();
            this.pendingData.put(socket, queue);
          queue.add(ByteBuffer.wrap(data));
        // Finally, wake up our selecting thread so it can make the required changes
        this.selector.wakeup();
      public void run()
        while (true)
          try
            // Process any pending changes
            synchronized (this.pendingChanges)
              Iterator changes = this.pendingChanges.iterator();
              while (changes.hasNext())
                ChangeRequest change = (ChangeRequest) changes.next();
                switch (change.type)
                  case ChangeRequest.CHANGEOPS:
                    SelectionKey key = change.socket.keyFor(this.selector);
                    key.interestOps(change.ops);
                    break;
                  case ChangeRequest.REGISTER:
                    change.socket.register(this.selector, change.ops);
                    break;
              this.pendingChanges.clear();
            // Wait for an event one of the registered channels
            this.selector.select();
            // Iterate over the set of keys for which events are available
            Iterator selectedKeys = this.selector.selectedKeys().iterator();
            while (selectedKeys.hasNext())
            System.out.println( " ----run 5 " ) ;
              SelectionKey key = (SelectionKey) selectedKeys.next();
              selectedKeys.remove();
              if (!key.isValid())
                continue;
              // Check what event is available and deal with it
              if (key.isConnectable())
                this.finishConnection(key);
              else if (key.isReadable())
                this.read(key);
              else if (key.isWritable())
                this.write(key);
          catch (Exception e)
            e.printStackTrace();
      private void read(SelectionKey key) throws IOException {
        System.out.println( "---------read 1 " ) ;
        SocketChannel socketChannel = (SocketChannel) key.channel();
        // Clear out our read buffer so it's ready for new data
        this.readBuffer.clear();
        System.out.println( "---------read 2 " + readBuffer.capacity()) ;
         readBuffer = ByteBuffer.allocate( bufferByteA.length  ) ;
        // Attempt to read off the channel
    //    int numRead;
        try {
    //      numRead = socketChannel.read(this.readBuffer);
          readFully( readBuffer , socketChannel ) ;
        } catch (IOException e) {
          // The remote forcibly closed the connection, cancel
          // the selection key and close the channel.
          key.cancel();
          socketChannel.close();
          return;
    //    if (numRead == -1) {
    //      // Remote entity shut the socket down cleanly. Do the
    //      // same from our end and cancel the channel.
    //      key.channel().close();
    //      key.cancel();
    //      return;
        // Handle the response
        this.handleResponse(socketChannel, this.readBuffer.array(), readBuffer.capacity() );
      private void handleResponse(SocketChannel socketChannel, byte[] data, int numRead) throws IOException {
        // Make a correctly sized copy of the data before handing it
        // to the client
        byte[] rspData = new byte[numRead];
        // Look up the handler for this channel
        RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
        // And pass the response to it
        if (handler.handleResponse(rspData)) {
          // The handler has seen enough, close the connection
          socketChannel.close();
          socketChannel.keyFor(this.selector).cancel();
      private void write(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        readBuffer.flip() ;
        List queue = null ;
        synchronized (this.pendingData) {
          queue = (List) this.pendingData.get(socketChannel);
          writeFully( readBuffer , socketChannel ) ;
          // Write until there's not more data ...
          while (!queue.isEmpty()) {
    //        ByteBuffer buf = (ByteBuffer) queue.get(0);
    //        socketChannel.write(buf);
    //        writeFully( buf , socketChannel ) ;
    //        if (buf.remaining() > 0) {
    //          // ... or the socket's buffer fills up
    //          break;
            queue.remove(0);
          if (queue.isEmpty()) {
            // We wrote away all data, so we're no longer interested
            // in writing on this socket. Switch back to waiting for
            // data.
            key.interestOps(SelectionKey.OP_READ);
      private void finishConnection(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        // Finish the connection. If the connection operation failed
        // this will raise an IOException.
        try {
          socketChannel.finishConnect();
        } catch (IOException e) {
          // Cancel the channel's registration with our selector
          System.out.println(e);
          key.cancel();
          return;
        // Register an interest in writing on this channel
        key.interestOps(SelectionKey.OP_WRITE);
      private SocketChannel initiateConnection() throws IOException {
        // Create a non-blocking socket channel
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        // Kick off connection establishment
        socketChannel.connect(new InetSocketAddress(this.hostAddress, this.port));
    //    socketChannel.finishConnect() ;
        // Queue a channel registration since the caller is not the
        // selecting thread. As part of the registration we'll register
        // an interest in connection events. These are raised when a channel
        // is ready to complete connection establishment.
        synchronized(this.pendingChanges) {
          this.pendingChanges.add(new ChangeRequest(socketChannel, ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
        return socketChannel;
      private Selector initSelector() throws IOException {
        // Create a new selector
        return SelectorProvider.provider().openSelector();
      public static void main(String[] args) {
        try {
          NioClient client = new NioClient(InetAddress.getByName("healsoft1"), 9090);
          Thread t = new Thread(client);
          t.setDaemon(true);
          t.start();
          RspHandler handler = new RspHandler();
          client.readBytesFromFile( handler ) ;
        } catch (Exception e) {
          e.printStackTrace();
      private void readBytesFromFile( RspHandler handler ) throws IOException
        File file = new File( "Y:/output.txt") ;
        bufferByteA = getBytesFromFile( file ) ;
        readBuffer = ByteBuffer.allocate(bufferByteA.length ) ;
        readBuffer.put( bufferByteA , 0 , bufferByteA.length ) ;
        send(bufferByteA , handler);
        handler.waitForResponse();
      private static void readFully(ByteBuffer buf, SocketChannel socket) throws IOException
        System.out.println( "readFully  : " ) ;
        int len = buf.limit() - buf.position();
        int count = 0 ;
        while (len > 0)
          len -= socket.read(buf);
      private void writeFully(ByteBuffer buf , SocketChannel socketChannel) throws IOException
        System.out.println( "writeFully  : " ) ;
        int len = buf.limit() - buf.position() ;
        SocketChannel socket = socketChannel ;
        socket.open();
        while (len > 0)
          len -= socket.write(buf);
      private static byte[] getBytesFromFile(File file) throws IOException
        InputStream is = new FileInputStream(file);
        // Get the size of the file
        long length = file.length();
             * You cannot create an array using a long type. It needs to be an int
             * type. Before converting to an int type, check to ensure that file is
             * not loarger than Integer.MAX_VALUE;
        if (length > Integer.MAX_VALUE)
          System.out.println("File is too large to process");
          return null;
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ( (offset < bytes.length)
                ( (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) )
                offset += numRead;
        // Ensure all the bytes have been read in
        if (offset < bytes.length)
          throw new IOException("Could not completely read file " + file.getName());
        is.close();
        return bytes;
      public static String printTimeWithMilliSec(long l )
        Date date = new Date( l ) ;
        SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss SSS");
        return f.format(date);
    }

    Data transfer rate for a single client is unlikely to be effected by using NIO or old blocking IO. The important factor is the maximum transfer rate you can get between the sender and receiver.
    You should be able to get 0.5-1.0 MB per second for each 10 Mbit per second of available bandwidth. Your timings suggest you are getting about a 10-20 Mbit/s link speed.

  • Security During File transfer

    hi,
    i have done a file transfer program in Java which transfers a file from one PC to another.
    i want tht my file (any text document ) should get transfered in secured manner. Like there should be cryptography and authentication both involved.
    how should i go about it ?

    My First preference would be to use SecuredSocket using Certificate.
    If you can not use Secured Socket, You can use a private-key and public key to encrypt/decrypt the data.
    I am assuming that you are sending file(s) from a local server to a remote server.
    You shoud create Key Pair Generator to generate public/private key and store them in a secured files in your remote server.
    Copy the public key to the local server using a secured way. (copy it using a ssh/scp).
    Then, you can encrypt your file content using the public key and send it to the remote server. The remote server should be able to decrypt using the private key and Only the remote server w/ private key will be able to decrypt and get the original content.
    Again, this is just one way to do it. If this needs to be a production code, I would suggest that you get a Certificate from a Certificate Authority such as VeriSign.
    If you need some help, drop me an email ([email protected])

  • Plz hel for file transfer using zmodem protocol

    someoe plz help me. i have to devlop an application that transfers files betwn 2 pcs(both ways) using dial up connection, further it should autodial the connection at periodic times.
    i am trying to use Zmodem file transfer protocol. i succseed in sending string (for test)using my sender program with hyper terminal open on the other hand. it prints the string. but when i use my receive program, similar to given in samples(simpleread.java) it doesnt work.
    actually when the ring comes from the sender how to send command to modem to hang up and connect to the calling pc if there are any such commands then plz help.
                                  ----sameer

    someoe plz help me. i have to devlop an application
    that transfers files betwn 2 pcs(both ways) using dial
    up connection, further it should autodial the
    connection at periodic times.
    i am trying to use Zmodem file transfer protocol. i
    succseed in sending string (for test)using my sender
    program with hyper terminal open on the other hand. it
    prints the string. but when i use my receive program,
    similar to given in samples(simpleread.java) it doesnt
    work.
    actually when the ring comes from the sender how to
    send command to modem to hang up and connect to the
    calling pc if there are any such commands then plz
    help.
    ----sameerU ddnt abrvt nuf. I r3r1t 4 U.
    Sum1 plzz hep m3. i 1/2 2 dvlop app taht xfer fil betwn 2 pcs(bth wys)...

  • Proxy Server in File Transfer System

    Hi, I need to write out a file transfer system through a proxy server for my project
    All the while i was writing a file transfer system directly from client to server without any security issue
    Anyway, the scope is given as below, and i know it needs the JSSE package to come out a SSLSocket and SSLServerSocket.
    The question is...
    1. can i use NIO with JSSE included?
    2. how to come out a java proxy server? is there any tutorial i can read through?
    The scope is given as below
    1) Proxy server
    * perform tunning and keep the linking between file transfer host and client
    * authenticate the file transfer client using CA certificate to establish SSL connection
    * Once authorised, need to establish another SSL connection to host engine
    2) File Transfer Manager at Client
    * To initiate SSL connection to proxy server
    * To open two type of connection: command and file connection
    * The command connection is always keep alive
    * For the file connection, the system required to re-open another connection after send file to host
    * Auto-reconnect to server when the connection is down
    * Re-handshake the SSL connection when the channel is inactive for sometime
    3) File Transfer Manager at host
    * To authenticate the proxy server and authorise the client before establish the connection
    * Manage the connection
    * request to client to open new connection (by sending command) when there is no file connection available to send file to client
    * Request for re-handshake the SSL connection when the channel is inactive for sometime

    Hi,
    It is a new feature of SMB3 named SMB MultiChannel, which helps copy files through multiple NICs. 
    Detailed information please see:
    http://blogs.technet.com/b/josebda/archive/2012/05/13/the-basics-of-smb-multichannel-a-feature-of-windows-server-2012-and-smb-3-0.aspx
    As mentioned you can disable or enable it with following steps:
    2.2. Disabling
    SMB Multichannel is enabled by default and there is typically no need to disable it. 
    However, if you want to disable SMB Multichannel (for testing purposes, for instance), you can use the following PowerShell cmdlets:
    On the SMB server side:
    Set-SmbServerConfiguration -EnableMultiChannel $false
    On the SMB client side:
    Set-SmbClientConfiguration -EnableMultiChannel $false
    Note: Disabling the feature on either the client or the server prevent the systems from using it.
    2.3. Re-enabling
    You can re-enable SMB Multichannel after you disabled it by using:
    On the SMB server side:
    Set-SmbServerConfiguration -EnableMultiChannel $true
    On the SMB client side:
    Set-SmbClientConfiguration -EnableMultiChannel $true
    Note: You need to enable the feature on both the client or the server to start using it again.
    If you have any feedback on our support, please send to [email protected]

  • File to file transfer

    hai
      i need the steps to be done for the scenerio file to file transfer,
      as if i am transfering a file from one R/3 to another R/3 system.
    what are the configuarion that is to be done for it?
    plz send me the detail steps.
    thx in advance. its urgent.

    Following are the links to weblogs which will help to develop the basic scenarios.
    /people/prateek.shah/blog/2005/06/08/introduction-to-idoc-xi-file-scenario-and-complete-walk-through-for-starters - IDoc to File
    /people/ravikumar.allampallam/blog/2005/03/14/abap-proxies-in-xiclient-proxy - ABAP Proxy to File
    /people/sap.user72/blog/2005/06/01/file-to-jdbc-adapter-using-sap-xi-30 - File to JDBC
    /people/prateek.shah/blog/2005/06/14/file-to-r3-via-abap-proxy - File to ABAP Proxy
    /people/venkat.donela/blog/2005/03/02/introduction-to-simplefile-xi-filescenario-and-complete-walk-through-for-starterspart1 - File to File Part 1
    /people/venkat.donela/blog/2005/03/03/introduction-to-simple-file-xi-filescenario-and-complete-walk-through-for-starterspart2 - File to File Part 2
    /people/ravikumar.allampallam/blog/2005/06/24/convert-any-flat-file-to-any-idoc-java-mapping - Any flat file to any Idoc
    /people/arpit.seth/blog/2005/06/27/rfc-scenario-using-bpm--starter-kit - File to RFC
    https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/1685 [original link is broken] [original link is broken] [original link is broken] [original link is broken] - File to Mail
    /people/jayakrishnan.nair/blog/2005/06/20/dynamic-file-name-using-xi-30-sp12-part--i - Dynamic File Name Part 1
    /people/jayakrishnan.nair/blog/2005/06/28/dynamic-file-namexslt-mapping-with-java-enhancement-using-xi-30-sp12-part-ii - Dynamic File Name Part 2
    /people/michal.krawczyk2/blog/2005/03/07/mail-adapter-xi--how-to-implement-dynamic-mail-address - Dynamic Mail Address
    /people/siva.maranani/blog/2005/05/25/understanding-message-flow-in-xi - Message Flow in XI
    /people/krishna.moorthyp/blog/2005/06/09/walkthrough-with-bpm - Walk through BPM
    /people/siva.maranani/blog/2005/05/22/schedule-your-bpm - Schedule BPM
    /people/sriram.vasudevan3/blog/2005/01/11/demonstrating-use-of-synchronous-asynchronous-bridge-to-integrate-synchronous-and-asynchronous-systems-using-ccbpm-in-sap-xi - Use of Synch - Asynch bridge in ccBPM
    https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/1403 [original link is broken] [original link is broken] [original link is broken] [original link is broken] - Use of Synch - Asynch bridge in ccBPM
    /people/michal.krawczyk2/blog/2005/08/22/xi-maintain-rfc-destinations-centrally - Maintain RFC destination centrally
    /people/sravya.talanki2/blog/2005/08/18/triggering-e-mails-to-shared-folders-of-sap-is-u - Triggering Email from folder
    /people/sravya.talanki2/blog/2005/08/17/outbound-idocs--work-around-using-party - Handling different partners for IDoc
    /people/siva.maranani/blog/2005/08/27/modeling-integration-scenario146s-in-xi - Modeling Integration Scenario in XI
    /people/michal.krawczyk2/blog/2005/08/25/xi-sending-a-message-without-the-use-of-an-adapter-not-possible - Testing of integration process
    /people/michal.krawczyk2/blog/2005/05/25/xi-how-to-add-authorizations-to-repository-objects - Authorization in XI
    http://help.sap.com/saphelp_nw04/helpdata/en/58/d22940cbf2195de10000000a1550b0/content.htm - Authorization in XI
    /people/michal.krawczyk2/blog/2005/09/09/xi-alerts--step-by-step - Alert Configuration
    /people/michal.krawczyk2/blog/2005/09/09/xi-alerts--troubleshooting-guide - Trouble shoot alert config
    /people/sameer.shadab/blog/2005/09/21/executing-unix-shell-script-using-operating-system-command-in-xi - Call UNIX Shell Script
    /people/sravya.talanki2/blog/2005/11/02/overview-of-transition-from-dev-to-qa-in-xi - Transport in XI
    /people/r.eijpe/blog/2005/11/04/using-abap-xslt-extensions-for-xi-mapping - Using ABAP XSLT Extensions for XI Mapping
    /people/prasad.ulagappan2/blog/2005/06/07/mail-adapter-scenarios-150-sap-exchange-infrastructure - Mail Adaptor options
    /people/pooja.pandey/blog/2005/07/27/idocs-multiple-types-collection-in-bpm - Collection of IDoc to Single File

  • Display progress of file transfer

    I made a app that uses tcp sockets to transfer a file im using ObjectOutputStream/ObjectInputStream. The thread that downloads the file has:
    package chat;
    import javax.swing.*;
    import java.net.Socket;
    import java.net.URL;
    import java.io.*;
    public class DownloadSocket extends Thread{
        Socket peer;
        ObjectInputStream obin;
        FileOutputStream fout;
        String fileName;
        String filePath;
        Thread runner;
        JFrame parent;
        public DownloadSocket(Socket peer, JFrame parent){
    this.parent = parent;
         try{        obin=newObjectInputStreamnewBufferedInputStreampeer.getInputStream()));
                start();
            }catch(IOException ioe){}
        public void start(){
            runner = new Thread(this);
            runner.start();
        public void run(){
            try {
                fileName = (String)obin.readObject();
                byte[] b = (byte[])obin.readObject();
                fout = new FileOutputStream(fileName);
                fout.write(b);
                JOptionPane.showMessageDialog(parent,"Received File " + fileName,"Confirmation",JOptionPane.INFORMATION_MESSAGE);
            }catch(Exception e){ }
            finally{
                try{
                    runner = null;
                    fout.close();
                    obin.close();
                    peer.close();
                }catch(Exception e){}
        }How do I get the percentage of the transfer or how many bytes are sent at any given time so i can use it to update a JProgress bar at any given time. The max value for the progress bar ill be the number of byte to send and this class can send an update to it every second or so. This class send the whole file in one go so im not sure.
    I also saw another file transfer snippet that gets the byte count sent, but i'd like to do it this way if possible. The other way was:
    try{
                byte[] buf = new byte[1024];
                    OutputStream os = socket.getOutputStream();
                    BufferedOutputStream out = new BufferedOutputStream(os,1024);
                    String file = "test.exe"
                    FileInputStream in = new FileInputStream(file);
                    int i;
                    int bytecount=0;
                    while ((i = in.read(buf,0,1024)) != -1){
                    bytecount=bytecount+1024;
                    out.write(buf,0,i);
                    out.flush();
                in.close();
                    out.close();
                    System.out.println("Bytes Sent :"+bytecount);
            catch (IOException e){
                System.out.println(e);
            try {
                socket.close();
            catch (IOException e){
                System.out.println(e);

    Have you considered using a ProgressMonitorInputStream?

  • JProgressBar and file transfer

    Hi, I am trying to use a JProgressBar to determine how many bytes have been sent so far. I have constructed the JProgressBar with the maximum size of the file size. For each 'segment' of the file sent, the progress bar should increment using the setProgress() within the SwingWorker class. If I print the values out, they appear to be correct. However, if I use setProgress() the file transfer seems to fail (not even begin).
    Here's the relevant code:
    public class FileTracker extends JDialog implements PropertyChangeListener {
         private JPanel mainPnl = new JPanel(new BorderLayout());
         private JPanel progressBarPnl = new JPanel(new BorderLayout());
         private JPanel midPnl = new JPanel(new GridBagLayout());
         private JPanel bottomPnl = new JPanel(new GridBagLayout());
         private JLabel fileNameLbl = new JLabel("File name: ");
         private JLabel fileNamexLbl = new JLabel();
         private JLabel sizeLbl = new JLabel("File size: ");
         private JLabel sizexLbl = new JLabel();
         private JButton cancelBtn = new JButton("Cancel");
         private JProgressBar progressBar;
         private FileSender fileSender;
         private FileReceiver fileReceiver;
         private File file;
         public FileTracker(JFrame parent, String ip, int port, File file) {
              super (parent);
              this.file = file;
              fileSender = new FileSender(ip, port, file);
              fileSender.addPropertyChangeListener(this);
              fileSender.execute();
              setLocationRelativeTo(null);
              progressBar = new JProgressBar();
              progressBar.setMaximum((int)file.length());
              add(progressBarPanel());
              setResizable(false);
              setTitle("File sending..");
              pack();
              setVisible(true);
         private JPanel progressBarPanel() {
              progressBar.setValue(0);
              progressBar.setEnabled(true);
              progressBar.setStringPainted(true);
              progressBar.setIndeterminate(true);
              progressBarPnl.add(progressBar, BorderLayout.CENTER);
              return progressBarPnl;
         public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                if (progressBar.isIndeterminate())
                     progressBar.setIndeterminate(false);
                progressBar.setValue(progress);
                if (fileSender != null && fileSender.isDone())
                     progressBar.setString("Transfer finished");
                if (fileReceiver != null && fileReceiver.isDone())
                     progressBar.setString("Transfer finished");
    }The SwingWorker:
    public class FileSender extends SwingWorker<Void, Void> {
         private Socket socket;
         private FileInputStream fileIn;
         private OutputStream output;
         private File file;
         private byte buffer[];
         private int bufferSize;
         int bytesRead;
         int progress = 0;
         public FileSender(String ipAddress, int port, File file) {
              try {
                   System.out.printf("NOTICE: FileSender initialised. Sending to:%s on port: %d\n", ipAddress, port);
                   socket = new Socket(InetAddress.getByName(ipAddress), port);
                   output = socket.getOutputStream();
                   bufferSize = socket.getSendBufferSize();
                   buffer = new byte[bufferSize];
                   this.file = file;
                   setProgress(0);
              } catch (UnknownHostException e) {
                   // THE USER MUST BE INFORMED THAT THE RECIPIENT COULD NOT BE RESOLVED
                   e.printStackTrace();
              } catch (java.net.ConnectException ce) {
                   // INFORM THE USER THAT THE RECIPIENT COULD NOT BE REACHED
                   ce.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public Void doInBackground() {
                   sendFile();
              return null;
         public void sendFile() {
              System.out.printf("NOTICE: Sending file %s   %d bytes formed of %d segments.\n", file.getName(), file.length(), file.length()/bufferSize < 1 ? 1 : file.length()/bufferSize);
              try {
                   fileIn = new FileInputStream(file);
                   while ((bytesRead = fileIn.read(buffer)) > 0) {
                        output.write(buffer, 0 , bytesRead);
                        progress = progress + bufferSize;
                        if (progress  < file.length())
                             setProgress(progress);
                        else
                             setProgress((int)file.length());
                   output.close();
                   fileIn.close();
                   socket.close();
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
              } catch (IOException ioe) {
                   ioe.printStackTrace();
    }This has been bugging me for a long time. Any help/suggestions much appreciated.

    when you create an SSCCE and get rid of all the File, socket, streams and whatnot (something that you should do next time), you notice something funny:
    import java.awt.BorderLayout;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingWorker;
    public class FileTracker extends JDialog implements PropertyChangeListener
        private static final int MAX = 500;
        private JPanel progressBarPnl = new JPanel(new BorderLayout());
        private JProgressBar progressBar;
        private FileSender fileSender;
        private FileReceiver fileReceiver;
        public FileTracker(JFrame parent)
            super(parent);
            fileSender = new FileSender(MAX);
            fileSender.addPropertyChangeListener(this);
            fileSender.execute();
            setLocationRelativeTo(null);
            progressBar = new JProgressBar();
            progressBar.setMaximum(MAX);
            add(progressBarPanel());
            setResizable(false);
            setTitle("File sending..");
            pack();
            //setVisible(true);
        private JPanel progressBarPanel()
            progressBar.setValue(0);
            progressBar.setEnabled(true);
            progressBar.setStringPainted(true);
            progressBar.setIndeterminate(true);
            progressBarPnl.add(progressBar, BorderLayout.CENTER);
            return progressBarPnl;
        public void propertyChange(PropertyChangeEvent evt)
            //if ("progress" == evt.getPropertyName()) // *** avoid doing this
            if ("progress".equals(evt.getPropertyName()))
                int progress = (Integer) evt.getNewValue();
                progressBar.setValue(progress);
                System.out.println("progress is: " + progress);
                if (fileSender != null && fileSender.isDone())
                    progressBar.setString("Transfer finished");
                    System.out.println("file sender is done");
                if (fileReceiver != null && fileReceiver.isDone())
                    progressBar.setString("Transfer finished");
                    System.out.println("file receiver is done");
        private class FileReceiver
            public boolean isDone()
                return false;
        private class FileSender extends SwingWorker<Void, Void>
            private int max;
            private int bufferSize;
            int bytesRead;
            int progress = 0;
            public FileSender(int max)
                this.max = max;
                System.out.println("NOTICE: FileSender initialised. ");
                bufferSize = max;
                setProgress(0);
            public Void doInBackground()
                sendFile();
                return null;
            public void sendFile()
                System.out.println("NOTICE: Sending file ");
                System.out.println("Max = " + max);
                bufferSize = 10;
                while (progress < max)
                    try
                        Thread.sleep(100);
                    catch (InterruptedException e)
                        e.printStackTrace();
                    progress += bufferSize;
                    if (progress < max)
                        setProgress(progress);
                    else
                        setProgress(max);
                System.out.println("after while loop");
        private static void createAndShowUI()
            JFrame frame = new JFrame("FileTracker");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            FileTracker filetracker = new FileTracker(frame);
            filetracker.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }The SwingWorker stops when only 20% of "file transfer" has occurred, but when the progress has reached 100. Then if you go into the [SwingWorker API for setProgress|http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html#setProgress(int)] , you see why the program is stopping here: the SwingWorker stops when its progress property reaches 100. So you must change this to a ratio rather than total bytes.

  • Copying complete directory structure using java.io.File

    Is there a solution to problem when you want to copy a complete directory structure using java.io.File class as you can copy when using FTP connection.

    Is there a solution to problem when you want to copy
    a complete directory structure using java.io.File
    class as you can copy when using FTP connection.FTP does not have a command to transfer all the files in a directory. FTP clients implement this by invoking single file transfer for each file in a directory.

Maybe you are looking for

  • How do I change the scratch disk?

    How do I edit disk ? - I'm getting the "disk is full" warning. How do I edit scratch disk ?

  • Can I use existing repository for master repository?

    can I use existing repository (for example repository from oracle designer ) for master repository? could you give me please an explanation thanks

  • Manual controls and LCD tilt on compacts?

    I shoot primarily with compact Canon's. I have Powershots and Elphs. I do a lot of macro work and shoot mostly in manual mode. I like physical buttons, rings, wheels and especially the new front ring that can be set to aperture or MF (simulates a DSL

  • Delete group increase file size

    In LabVIEW I create a TDMS file using DAQmx Configure Logging.  Since my users want to control when data is being written to the file, I make use of the Loggingause property.  Very often two groups of data are created in the TDMS file; one containing

  • 29Gig of photos on drive, but only 1.8G in Iphoto - where are they?

    Hello all - I found that my drive was nearly full, and had to make some room, so I found many pics which I no longer needed, and thus deleted them, however I found this barely touched what the profiler says I have for photos/video on my drive. It say