Put ftp commands inside Java code?

Hi.
I've no problems with ftp with exec(...), using an external ftp text file containing the ftp commands.
But can I pullthe ftp commands into the Java codes?
The reason is we don't want people accidentally messing around with the ftp commands

you can also use URLs for FTPing:
     * If the client needs to connect to the server through a proxy, this method sets the JVM FTP proxy settings.
     * @param proxyHost Host name of proxy.
     * @param proxyPort Port number of proxy host.
    public void setProxy(String proxyHost, int proxyPort) {
        if (proxyHost != null) {
            System.getProperties().put("ftpProxySet", "true");
            System.getProperties().put("ftpProxyHost", proxyHost);
            System.getProperties().put("ftpProxyPort", ""+proxyPort);
    }//setProxy()
     * Upload a file to a FTP server. A FTP URL is generated with the following syntax:
     * <code>ftp://user:password@host:port/urlpath;type=i</code>.
     * @param ftpServer FTP server address.
     * @param user Optional user name to login.
     * @param pwd Optional password for <i>user</i>.
     * @param fileName Destination file name on FTP server (with optional preceeding relative path, e.g. one/two/three.txt).
     * @param source Source file to upload.
     * @throws Exception on error.
    public void upload(String ftpServer, String user, String pwd, String fileName, File source) throws MalformedURLException,
            IOException {
        if (ftpServer != null && fileName != null && source != null) {
            StringBuffer sb = new StringBuffer("ftp://");
            if (user != null && pwd != null) {
                sb.append(user);
                sb.append(':');
                sb.append(pwd);
                sb.append('@');
            sb.append(ftpServer);
            sb.append('/');
            sb.append(fileName);
            sb.append(";type=i"); //a=ASCII mode, i=image (binary) mode, d= file directory listing
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                URL url = new URL(sb.toString());
                URLConnection urlc = url.openConnection();
                bos = new BufferedOutputStream(urlc.getOutputStream());
                bis = new BufferedInputStream(new FileInputStream(source.getName()));
                int i;
                while ((i = bis.read()) != -1) {
                    bos.write(i);
            } finally {
                if (bis != null) { try { bis.close(); } catch (IOException ioe) { /* ignore*/ } }
                if (bos != null) { try { bos.close(); } catch (IOException ioe) { /* ignore*/ } }
    }//upload()
      * Download a file from a FTP server. A FTP URL is generated with the following syntax:
     * <code>ftp://user:password@host:port/filePath;type=i</code>.
      * @param ftpServer FTP server address (with optional port ':<port>').
      * @param user Optional user name to login.
      * @param pwd Optional password for <i>user</i>.
      * @param fileName Name of file to download (with optional preceeding relative path, e.g. one/two/three.txt).
      * @param destination Destination file to save.
                      * @throws Exception on error.
     public void download(String ftpServer, String user, String pwd, String fileName, File destination) throws MalformedURLException,
            IOException {
        if (ftpServer != null && fileName != null && destination != null) {
            StringBuffer sb = new StringBuffer("ftp://");
            if (user != null && pwd != null) {
                sb.append(user);
                sb.append(':');
                sb.append(pwd);
                sb.append('@');
            sb.append(ftpServer);
            sb.append('/');
            sb.append(fileName);
            sb.append(";type=i"); //a=ASCII mode, i=image (binary) mode, d= file directory listing
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                URL url = new URL(sb.toString());
                URLConnection urlc = url.openConnection();
                bis = new BufferedInputStream(urlc.getInputStream());
                bos = new BufferedOutputStream(new FileOutputStream(destination.getName()));
                int i;
                while ((i = bis.read()) != -1) {
                    bos.write(i);
            } finally {
                if (bis != null) { try { bis.close(); } catch (IOException ioe) { /* ignore*/ } }
                if (bos != null) { try { bos.close(); } catch (IOException ioe) { /* ignore*/ } }
    }//download()

Similar Messages

  • How to run a command prompt " command " through java code

    hi all,
    There is a command
    "java -jar selenium-server.jar -interactive"
    which i am running through command prompt after going to D:\MyFolder\Examples .
    i want to execute this command using java code .please help

    This has already been answered in your other two threads on this topic - http://forum.java.sun.com/thread.jspa?threadID=5221221&messageID=9898287#9898287 and http://forum.java.sun.com/thread.jspa?threadID=5221223&messageID=9898290#9898290.
    For some reason you don't want to read the reference that tells you exactly how to do what you want and how to avoid the pitfalls - http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html .

  • Running a command from java code

    hi all,
    There is a command
    "java -jar selenium-server.jar -interactive"
    which i am running through command prompt after going to D:\MyFolder\Examples .
    i want to execute this command using java code .please help

    subratjyetki wrote:
    please answer in detail or if posible can u give the code for thisOnce more -
    The detail is given in the reference. Why don't you read it?
    I could give you the code but it will cost you �100 per hour.

  • To run a command using java code

    hi all,
    There is a command
    "java -jar selenium-server.jar -interactive"
    which i am running through command prompt after going to D:\MyFolder\Examples .
    i want to execute this command using java code .please help

    subratjyetki wrote:
    please answer in detail or if posible can u give the code for thisThe detail is given in the reference. Why don't you read it?
    I could give you the code but it will cost you ?100 per hour.

  • Calling Windows XP FTP Command in java

    Hi there!
    Need help in calling Windows XP FTP command in java:
    executing the FTP command in DOS works well, but when I tried calling it in java using Process and Runtime objects, it successfully transferred the files from remote to my local pc... but I seemed to be stuck with .exec() and cannot continue with the other statements.
    I know that I can use eFTPj or Apache Commons Net .. but I have no more time to study it since I have no more time left.
    Any idea or suggestion? I badly need your help�
    Take care and God bless,
    MaDz

    Solution:
    Better use Apache Commons Net - FTP for greater java support.

  • Spanish characters getting garbled while executing command using Java code

    Hi,
    I try to execute a command using java code. output of the command contains spanish characters. Few of these characters getting garbled after the command execution.
    Runtime r = Runtime.getRuntime();
              Process p = null;
    String pgm="ipconfig /all";
              try
                        p = r.exec(pgm);
    BufferedReader br=new BufferedReader(new InputStreamReader
                                  (p.getInputStream()));
    while((val = br.readLine()) != null){ System.out.println(val);
              catch (Exception e)
                        return (null);
    I tried to run the code using -Duser.language=es -Duser.region=ES -Dfile.encoding=Cp850, but this did nt help. I could see the outputs properly in command prompt,
    If i redirect the output to a text file , it is getting garbled,
    Please let me know to solve this issue.

    884543 wrote:
    Hi,
    I try to execute a command using java code. output of the command contains spanish characters. Few of these characters getting garbled after the command execution.
    Runtime r = Runtime.getRuntime();
              Process p = null;
    String pgm="ipconfig /all";
              try
                        p = r.exec(pgm);
    BufferedReader br=new BufferedReader(new InputStreamReader
                                  (p.getInputStream()));
    while((val = br.readLine()) != null){ System.out.println(val);
              catch (Exception e)
                        return (null);
    I tried to run the code using -Duser.language=es -Duser.region=ES -Dfile.encoding=Cp850, but this did nt help. I could see the outputs properly in command prompt,
    If i redirect the output to a text file , it is getting garbled,
    Please let me know to solve this issue.Set the character set to UTF-8 to your InputStreamReader, for More details on usage refer the java api :
    http://download.oracle.com/javase/6/docs/api/java/io/InputStreamReader.html

  • Execute DOS command inside java

    I have a java program that reads each new user from an inputfile and writes that same user to an output file. The program works fine and is shown below:
    import java.io.*;
    public class FileStreamsTest {
    public static void main(String[] args) {
    try {
    File inputFile = new File("newbousrs.txt");
    File outputFile = new File("outagain.txt");
    FileInputStream fis = new FileInputStream(inputFile);
    FileOutputStream fos = new FileOutputStream(outputFile);
    int c;
    while ((c = fis.read()) != -1) {
    fos.write(c);
    fis.close();
    fos.close();
    } catch (FileNotFoundException e) {
    System.err.println("FileStreamsTest: " + e);
    } catch (IOException e) {
    System.err.println("FileStreamsTest: " + e);
    What I would like to do after each write is to execute a DOS command that looks something like this: supervsr.exe -USER username -PASS password -IMPORTUSERS importfile.txt
    The DOS command above will add each user to the system I want to as the loop goes through each user record.
    How do I execute the DOS command above inside java?

    Tried what but still having a problem...here is my code:
    import java.io.*;
    public class ReadSource {
    public static void main(String[] arguments) {
    try {
    FileReader file = new FileReader("newbousrs.txt");
                                  //FileWriter letters = new FileWriter("outagain.txt");
                                  //PrintWriter pw = new PrintWriter(new FileWriter("outagain.txt"));
    BufferedReader buff = new BufferedReader(file);
                                  Runtime rt = Runtime.getRuntime();
    boolean eof = false;
    while (!eof) {
    String line = buff.readLine();
    if (line == null)
    eof = true;
    else
    System.out.println(line);
                                                 Process proc = rt.exec("\\Blowfish\\droot\\Program Files\\Business Objects\\BusinessObjects 5.0\\supervsr.exe -USER xxxxx -PASS yyyy -IMPORTUSERS \\Blowfish\\droot\\accsp\\public\\newusers\\newbousrs.txt");
                                                 //System.out.println(line.substring(4, 10));
                                                 //System.out.println(line.substring(3,line.indexOf(',',3)));
    buff.close();
    } catch (IOException e) {
    System.out.println("Error -- " + e.toString());
    There error I get is this:
    C:\jakarta-tomcat-4.0.3\webapps\webdav\WEB-INF\classes\accsp>java ReadSource
    NU,Public,Steve Mcnealy,Steve Mcnealy,U,N,N,Y,N,N,PC,F,Y,N,N
    Error -- java.io.IOException: CreateProcess: \Blowfish\droot\Program Files\Busin
    ess Objects\BusinessObjects 5.0\supervsr.exe -USER accsp -PASS fish -IMPORTUSERS
    \Blowfish\droot\accsp\public\newusers\newbousrs.txt error=3

  • Executing sqlplus / sqlldr command from java code

    hi,
    I have my application on one server(tomcat) and oracle server is installed on other server. i.e. Both are on different machine.
    Now i want to run sqlplus / sqlldr command on oracle server from my java code.
    Again my script for lodder command is in temp of tomcat.
    How to do that?
    Thanks,

    Hi,
    I am using JDBC to executed queries...but i need to run sqlplus command to run script if some condition is satisfied and same for sqllodder to load large record like 500000. This code is in the thread and is working fine for same machine. Need to execute it on another machine where oracle is installed.
    From command prompt i am able to run sqlplus on Oracle server. Same command I am not able to run from the code. I have shared bin direcotry of Oracle from server.
    Let me know if any query
    Regards,
    Edited by: Sun_Nut on Dec 16, 2007 9:53 PM

  • How to execute solaris lpd printing command from java code

    hi folk,
    I want to print a post script file on a network printer (my java code will receive the Printer's IP Address and the filename ) , i'm using the solaris lpd printing command :
    lpadmin -p banana_ps -o protocol=bsd,dest=IP -v /dev/null
    -m netstandard -T PS -I postscript
    my question is how execute this command from the java code :)
    i really appreciate ur advices

    Hi,
    See RunTime.getRuntime ().exec (...).
    Hope that help,
    Jack

  • Running windows command through java code

    Hello
    i want to execute jar.exe through java code , i have written following piece of code , but it isn't working
    ProcessBuilder processBuilder = new ProcessBuilder(new String[]{"cmd.exe","/c","%java_home%\\bin\\jar.exe"});
              Process process = processBuilder.start();
              BufferedReader inputReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
              String line = inputReader.readLine();
              while(line != null){
                   System.out.println(line);
                   line = inputReader.readLine();
    does anybody knows why
    Regards
    Edited by: Mayur Mitkari on Mar 5, 2013 10:19 PM
    Edited by: Mayur Mitkari on Mar 5, 2013 10:20 PM
    Edited by: Mayur Mitkari on Mar 5, 2013 10:20 PM

    sorry for that , but the
    Runtime runtime = Runtime.getRuntime();
              Process proc = runtime.exec(new String[]{"cmd.exe","/c","jar"});
              proc.waitFor();
    int i = proc.exitValue();
    this code was different from first one
    and in case of Process if runtime .exec is succesful it is wainting for long time , in this case i want if the runtime.exec is succesful something should be returned
    Regards

  • How to insert html table inside java code

    Hi,
    I want to send an email with data in table format(with rows and columns) .Please tell me how to achieve this in java code .I just want to know the code for making the table in java
    Please help me
    Thanks in advance

    NewUser7 wrote:
    Please tell me how to generate html tables in java. .. Do you know how to produce an HTML table in HTML?
    ..i dont have jspI did not mention JSP. Pure J2SE code can produce HTML, though if done in a web-app., it would generally be done using JSP or Servlets.
    Here is an example of producing HTML in J2SE.
    import javax.swing.*;
    class HtmlTable {
         public static void main(String[] args) {
              int[][] values = {
                   {1,3894,5387},
                   {2,4112,4459},
                   {3,4886,6076}
              String prefix = "<html><body><table>\n";
              final StringBuilder sb = new StringBuilder(prefix);
              sb.append("<tr>");
              sb.append("<th>");
              sb.append("Month");
              sb.append("</th>");
              sb.append("<th>");
              sb.append("Unit A<br>Sales");
              sb.append("</th>");
              sb.append("<th>");
              sb.append("Unit B<br>Sales");
              sb.append("</th>");
              sb.append("</tr>\n");
              for (int ii=0; ii<values.length; ii++) {
                   sb.append("<tr>");
                   for (int jj=0; jj<values[ii].length; jj++) {
                        sb.append("<td>");
                        sb.append("" + values[ii][jj]);
                        sb.append("</td>");
                   sb.append("</tr>\n");
              sb.append("</table>");
              sb.append("</body>");
              sb.append("</html>");
              Runnable r = new Runnable() {
                   public void run() {
                        JOptionPane.showMessageDialog(
                             null,
                             new JTextArea(sb.toString(),20,10) );
                        JOptionPane.showMessageDialog(
                             null,
                             new JLabel(sb.toString()) );
              SwingUtilities.invokeLater(r);
    As an aside, those terms are HTML (an abbreviation) Java (a proper name) & JSP (an abbreviation). Please try to use correct upper/lower case when using technical terms.

  • How to search inside java code?

    How to search for pattern in Java code from NWDS?  For example, I want to search for "wdThis" in java code.  Where to look for find or search button?

    Hi,
    You can also use CTRL+H key for searching any Java or non-Java code across all projects you have opened in your workspace.
    Just go to Project Explorer View and select any project, then press CTRL+H, a set of search option will show up.
    Hope it helps.
    Best regards,
    David.

  • Using ftp in core java code to transferring a file to other sys

    My mail id:[email protected]
    hi to all
    I am actually using this code for transforing a file from my system to side system of mine.but the code is compiling and when runing this code i am getting an error:
    java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at com.sshtools.j2ssh.net.SocketTransportProvider.<init>(Unknown Source)
    at com.sshtools.j2ssh.net.TransportProviderFactory.connectTransportProvider(Unknown Source)
    at com.sshtools.j2ssh.SshClient.connect(Unknown Source)
    at com.sshtools.j2ssh.SshClient.connect(Unknown Source)
    at com.sshtools.j2ssh.SshClient.connect(Unknown Source)
    at ftpsample1.main(ftpsample1.java:36)
    I am getting this error.
    friend is saying some proxy should should be installed in that other system.
    Plase help me..
    my code is:
    import java.io.File;
    import java.util.List;
    import java.io.*;
    import com.sshtools.j2ssh.SftpClient;
    import com.sshtools.j2ssh.SshClient;
    import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
    import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
    import com.sshtools.j2ssh.sftp.SftpFile;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    class ftpsample1
         public static void main(String[] args) {
         String username="administrator";
         String password="thota1976";
    try{
    // Make a client connection
    System.out.println("Before SSHCLIENT......");
    SshClient ssh = new SshClient();
         System.out.println("After SSHCLIETNT ......");
    // Connect to the host
    System.out.println("Connecting ......");
    System.out.println("ssh.connect ->9.182.54.70*************************......");
         ssh.connect("9.182.54.70");
    System.out.println("Connected***");
         // Create a password authentication instance
    PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
         // Get the users name
    pwd.setUsername(username);
         // Get the password
    pwd.setPassword(password);
         // Try the authentication
    int result = ssh.authenticate(pwd);
         System.out.println("ssh.authenticate(pwd):::" +result);
    System.out.println("AuthenticationProtocolState.COMPLETE:::***:" +AuthenticationProtocolState.COMPLETE);
              System.out.println("Beforet he AuthenticationProtocolState.COMPLETE ::");
         if (result == AuthenticationProtocolState.COMPLETE) {
              System.out.println("BOTH ARE SAME RESULT AND .COMPLETED*--------------");
    // The connection is authenticated we can now do some real work!
    SftpClient sftp = ssh.openSftpClient();
              sftp.put("c:/temp/Balaji.jpg");
                   System.out.println("after he AuthenticationProtocolState.COMPLETE ::");
    }catch(Exception e)
                        e.printStackTrace();
                        System.out.println("*****");
                        e.getMessage();

    You could use only Java classes without and 3rd party classes (com.sshtools.j2ssh) for doing this:
         * Upload a file to a FTP server. A FTP URL is generated with the following syntax:
         * <code>ftp://user:password@host:port/filePath;type=i</code>.
         * @param ftpServer FTP server address (incl. optional port ':portNumber').
         * @param user Optional user name to login.
         * @param pwd Optional password for <i>user</i>.
         * @param fileName Destination file name on FTP server (with optional preceeding relative path, e.g. "one/two/three.txt").
         * @param source Source file to upload.
         * @throws MalformedURLException, IOException on error.
        public void upload(String ftpServer, String user, String pwd, String fileName, File source) throws MalformedURLException, IOException {
            if (ftpServer != null && fileName != null && source != null) {
                StringBuffer sb = new StringBuffer("ftp://");
                if (user != null && pwd != null) { //need authentication?
                    sb.append(user);
                    sb.append(':');
                    sb.append(pwd);
                    sb.append('@');
                }//else: anonymous access
                sb.append(ftpServer);
                sb.append('/');
                sb.append(fileName);
                sb.append(";type=i"); //a=ASCII mode, i=image (binary) mode, d= file directory listing
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                try {
                    URL url = new URL(sb.toString());
                    URLConnection urlc = url.openConnection();
                    bos = new BufferedOutputStream(urlc.getOutputStream());
                    bis = new BufferedInputStream(new FileInputStream(source.getName()));
                    int i;
                    while ((i = bis.read()) != -1) { //read next byte until end of stream
                        bos.write(i);
                    }//next byte
                } finally {
                    if (bis != null) try { bis.close(); } catch (IOException ioe) { /* ignore*/ }
                    if (bos != null) try { bos.close(); } catch (IOException ioe) { /* ignore*/ }
            }//else: input unavailable
        }//upload()

  • Cannot call the execute command from java code

    Hello,
    I like to add a new user via a java web service.
    Establishing a connection to the OC4J MBean server is no problem. I also can execute the commands 'listAllCommands' and 'help' on the MBean. But if i try to call the execute command, i always get an NoSuchMethodException. Looking at the MBeanInfos 'execute' is listed there as an operation.
    Can anyone explain this to me?

    Hi,
    I basically used the code described at http://download.oracle.com/docs/cd/B32110_01/web.1013/b28952/mbeans.htm#CIHFDJBJ to connect to the MBeanServer.
    To invoke 'execute' i used
    MBeanServerConnection con= jmxCon.getMBeanServerConnection();
    con.invoke(new ObjectName(MBEAN_NAME), "execute", new Object[] { COMMAND }, new String[] {});
    where MBEAN_NAME is the ObjectName of the CommandService MBean and COMMAND is a String like "identity add ..."

  • Running a exe (java command) through Java Code

    Hi I have a program that runs on command line using java command.This program processes a text file that it takes as an argument.I have many files to process so I cannot give command for each individual file.
    Is it possible that I use Java command to run this program for many files in a loop?
    If yes HOW?

    It has many parameters but one parameter for input file. But I think this is not a problem, I can change it as you said.Now I have tried this code:
    Note:In this code I can change B.txt each time in a loop for new input file. (This is just for check)
    import java.io.*;
    public class Test3
         public static void main(String[] args)
              Runtime run = Runtime.getRuntime();
              try
    Process pp=run.exec("C:/Program Files/Java/jdk1.6.0/bin/java -mx300m -classpath  B.txt > sample-output.txt");
                   BufferedReader in =new BufferedReader(new InputStreamReader(pp.getErrorStream()));
                   String line;
                   while ((line = in.readLine()) != null)
                        System.out.println(line);
                   int exitVal = pp.waitFor();
                   System.out.println("Process exitValue: " + exitVal);
              catch (Exception e)
                   e.printStackTrace();
                   System.out.println(e.getMessage());
    } It compiles well but gives exception NoClassDefFound when I use java command to interpret it.Can u help?
    Edited by: kimskams on Jun 29, 2008 7:24 AM

Maybe you are looking for

  • Do pictures that are downloaded from a camera reverse course and go to photo stream on iPhone?

    I have some pictures that I did not take with my iphone but either with a canon camera or via capture on my laptop. When I put them in iphoto, they showed up in photostream on my iphone. WHY? How can I make sure that does not happen? Is there a setti

  • SRM confirmations result in zero value material documents

    We're on SRM 4.0 classic scenario. We currently have a situation where we create confirmations in SRM but some of them ended up with zero value material documents; therefore, no accounting documents are generated. It also means no accruals are booked

  • Failed start up-Grey screen ****

    Hi nice people. I own a –G4 imac 15” flat panel, running OSX10.2 Currently after turning on my computer I get the following- The start up tone, then a screen with the grey apple logo, I then get the spinning grey progress wheel and this is how the co

  • Search: Internet and my Content on 6220 - Internet...

    Hi Nokia 6220 and the Search Internet and my Content option on the StandBy screen (also under Menu | Internet | Search) On my phone this happily goes off to Google and brings a search result page to screen. However, when you click on a link to see th

  • Import video to iphone 3gs

    I work in the video industry and create video for other teams, once I create a short video, I usually email this to the team but would like to add the video to my iphone to show how it would look like. I can't seem to add any video, the format is in