Archiving File on Shared Folder in Linux using java code

Hi All,
I have a requirement wherein I have to ftp a file (Feed.txt) from windows FTP server to Linux machine1 and archive the same file (with timestamp suffixed on file name like Feed.txt_22April) on Linux Machine2. I am
trying to achieve this through java code. I am able to ftp the file(Feed.txt) from windows ftp server to Linux machine1 /opt/ftproot directory and archiving the same file under /opt/ftproot/archive directory of Linux
Machine1 with timestamp suffixed on file name.
My archiving requirement is still not achieved. So, for that I created a shared folder “/temp/shared” on Linux Machine2 and mounted the /temp/shared folder of Linux Machine2 on /opt/ftproot/archive folder of
Linux Machine1 using following command:
# mount LinuxMachine2: /temp/shared /opt/ftproot/archive
Note: I have given full permission on both the folders.
Logically, archiving the Feed.txt with timestamp in it name under /opt/ftproot/archive folder should create the file in /temp/shared folder of Linux Machine2. But instead of archiving the file on
/opt/ftproot/archive folder, it archive the file on /opt/ftproot folder.
In my java code, I have specified copyDir as “/opt/ftproot” and archiveDir as /opt/ftproot/archive”.
The code is being run from Linux Machine1 as a schedule task.
Please help.
PFB the code snippet:
package com.ftp;
import com.thortech.xl.scheduler.tasks.SchedulerBaseTask;
import org.apache.commons.net.ftp.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class FTPService extends SchedulerBaseTask {
     private static String targetDir="";
     private static String archiveDir="";
public void init() {
public void execute() {
try {
String server = "Machine1
String username = "username";
String password = "password";
String sourceDir = "C:\\Inetpub\\ftproot\\temp.txt";
//String archiveDir = "/home/ftproot1";
targetDir = getAttribute("Target Directory");
FTPClient ftp = new FTPClient();
* Connect to the server
ftp.connect(server);
ftp.login(username, password);
System.out.println("Connected to " + server + ".");
String[] names = ftp.listNames();
for (String name : names) {
System.out.println("Name = " + name);
* Get all file names that are present in the current working directory
FTPFile[] files = ftp.listFiles();
String fileName = "";
for (int i = 0; i < files.length; i++) {
if (files.isFile()) {
System.out.println("\t" + files[i].getName());
File file = new File(targetDir + File.separator +
files[i].getName());
FileOutputStream fos = new FileOutputStream(file);
* Copy the file to target system
ftp.retrieveFile(files[i].getName(), fos);
fos.close();
fileName = files[i].getName();
ftp.logout();
ftp.disconnect();
System.out.println("End of FTP....");
System.out.println("Calling fileCopy()");
System.out.println("Target Directory"+targetDir);
fileCopy(fileName,targetDir);
} catch (Exception e) {
e.printStackTrace();
public static String getDate() {
String sdate = "";
try {
     System.out.println("Inside getDate()");
Calendar date = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.0");
sdate = formatter.format(date.getTime());
} catch (Exception e) {
return sdate;
public void moveFile(String t) {
     try{
     System.out.println("inside moveFile");
System.out.println("Moving Files");
File fro = new File(t);
archiveDir = getAttribute("Archive Directory");
System.out.println("Archiving Directory"+archiveDir);
File to = new File(archiveDir);
boolean archived = fro.renameTo(new File(to, fro.getName()));
if (archived) {
System.out.println("FileArchived");
          /*String cmd="mv" +" "+t +" "+ "/home/ftproot/archive";
          System.out.println("Archive Directory"+archiveDir);
          System.out.println("Move Command"+cmd);
          Process SshProc =      (Runtime.getRuntime()).exec(cmd);
} catch (Exception e) {
e.printStackTrace();
public void fileCopy(String filename,String Directory) {
     try{
     //String ifile="/home/ftproot/sunny.txt";
          String ifile=targetDir+"/"+filename;
     String ofile=ifile+"_"+getDate();
     File f1 = new File(ifile);
     File f2 = new File(ofile);
     InputStream in = new FileInputStream(f1);
     //For Append the file.
//      OutputStream out = new FileOutputStream(f2,true);
     //For Overwrite the file.
     OutputStream out = new FileOutputStream(f2);
     byte[] buf = new byte[1024];
     int len;
     while ((len = in.read(buf)) > 0){
     out.write(buf, 0, len);
     in.close();
     out.close();
     System.out.println("File copied.");
     moveFile(ofile);
     }catch(Exception e)
     System.out.println("File copied."+e);
Cheers,
Sunny

sunnyajmera wrote:
Please help.If it was me....
- You are connecting to a ftp server. I am guessing you didn't write that.
- Get a flexible ftp client, there are many but make sure it shows you the ftp result codes.
- Figure out how and if the ftp server will do what you want.
If it does do what you want then ftp client will let you do the same thing.
If that ftp server doesn't allow you to do it then you must do one of the following
- Find a different server
- Change the requirements
- Find a way to impose the requirements using a tool in addition to ftp like some command executed through telnet.

Similar Messages

  • How to store files in shared-folder in background mode

    Hello All,
    My requirement seems to be simple but I have tried many ways in achieving this, but failed. So require the help in accomplishing this task.
    Requirement
    I have to create a program in SE38 which will create a internal table with data in it in .XML format(which I can achieve).
    My requirement is this .XML file needs to be placed in a shared-folder in "BACKGROUND MODE".
    I have tried using GUI_DOWNLOAD function module, but this FM only runs in Foreground mode and fails in Background mode. I have tried convincing my client that I will keep the file in Application Server as it is achievable using OPEN DATASET statements, but they are not willing to accept this.
    So can you please help me in achieving this task as I am not getting any solution how to keep the file in Shared-folder in BACKGROUND mode itself(not Foreground).
    Best Regards,
    Tousif

    Hi Sanjeev,
    I have just used normal GUI_DOWNLOAD FM. Please find my sample code below
    CALL FUNCTION 'GUI_DOWNLOAD'
         EXPORTING
    *       BIN_FILESIZE                    =
           filename                        = 'D:\Users\baigtomx\Desktop\TOUSIF.XML'
    *       FILETYPE                        = 'ASC'
    *       APPEND                          = ' '
    *       WRITE_FIELD_SEPARATOR           = ' '
    *       HEADER                          = '00'
    *       TRUNC_TRAILING_BLANKS           = ' '
    *       WRITE_LF                        = 'X'
    *       COL_SELECT                      = ' '
    *       COL_SELECT_MASK                 = ' '
    *       DAT_MODE                        = ' '
    *       CONFIRM_OVERWRITE               = ' '
    *       NO_AUTH_CHECK                   = ' '
    *       CODEPAGE                        = ' '
    *       IGNORE_CERR                     = ABAP_TRUE
    *       REPLACEMENT                     = '#'
    *       WRITE_BOM                       = ' '
    *       TRUNC_TRAILING_BLANKS_EOL       = 'X'
    *       WK1_N_FORMAT                    = ' '
    *       WK1_N_SIZE                      = ' '
    *       WK1_T_FORMAT                    = ' '
    *       WK1_T_SIZE                      = ' '
    *       WRITE_LF_AFTER_LAST_LINE        = ABAP_TRUE
    *       SHOW_TRANSFER_STATUS            = ABAP_TRUE
    *       VIRUS_SCAN_PROFILE              = '/SCET/GUI_DOWNLOAD'
    *     IMPORTING
    *       FILELENGTH                      =
         TABLES
           data_tab                        = lt_wo
    *       FIELDNAMES                      =
    *     EXCEPTIONS
    *       FILE_WRITE_ERROR                = 1
    *       NO_BATCH                        = 2
    *       GUI_REFUSE_FILETRANSFER         = 3
    *       INVALID_TYPE                    = 4
    *       NO_AUTHORITY                    = 5
    *       UNKNOWN_ERROR                   = 6
    *       HEADER_NOT_ALLOWED              = 7
    *       SEPARATOR_NOT_ALLOWED           = 8
    *       FILESIZE_NOT_ALLOWED            = 9
    *       HEADER_TOO_LONG                 = 10
    *       DP_ERROR_CREATE                 = 11
    *       DP_ERROR_SEND                   = 12
    *       DP_ERROR_WRITE                  = 13
    *       UNKNOWN_DP_ERROR                = 14
    *       ACCESS_DENIED                   = 15
    *       DP_OUT_OF_MEMORY                = 16
    *       DISK_FULL                       = 17
    *       DP_TIMEOUT                      = 18
    *       FILE_NOT_FOUND                  = 19
    *       DATAPROVIDER_EXCEPTION          = 20
    *       CONTROL_FLUSH_ERROR             = 21
    *       OTHERS                          = 22
       IF sy-subrc <> 0.
    * Implement suitable error handling here
       ENDIF.
    When I run this program in foreground mode, the file gets saved(here in the above example I have just used my desktop path. but the actual requirement is to store file in shared-folder i-e Network Drive).
    But when i run the same program in background mode, No file is getting stored.
    Regards,

  • Windows 2008 : How to Restrict Users to Copy file from Shared Folder

    Hello All,
    I need to Restrict Users to Copy file from Shared Folder. Please let me know is there any method to achieve this requirement.

    If user have Read permission, they can copy it. So actually you cannot restrict user from copy your files if they could read/edit.
    Some programs could help restrict users from edit/modify/copy the content of their files such as Office files, PDF files etc as Oscar said above.
    TechNet Subscriber Support in forum |If you have any feedback on our support, please contact [email protected]

  • Open a PDF file in linux using java

    Hi..
    How can I open a PDF file in linux using java.
    I am able to open PDF in windows and mac using this code
    in Windows
    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path_of_PDF);
    in mac
    Runtime.getRuntime().exec("open " + path_of_PDF);
    But nothing is working with linux.
    Please help
    Thanks

    One thread is enough:
    http://forum.java.sun.com/thread.jspa?threadID=5267458

  • Open PDF file in linux using java

    Hi..
    How can I open a PDF file in linux using java.
    I am able to open PDF in windows and mac using this code
    in Windows
    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path_of_PDF);
    in mac
    Runtime.getRuntime().exec("open " + path_of_PDF);
    But nothing is working with linux.
    Please help
    Thanks

    appi wrote:
    Hi.. I found the JDIC binary files. There are different binaries for all the plateform. Is there any solution which is independent of plateform.Yes, and we already told you: Use JDK6, which has those libraries built into the standard class library.
    How can I use these binaries in my existing project. does it work, If I place them at same place where other .class files are kept.Read the documentation of the JDIC project. I'm sure they answer this question in their FAQ.

  • Creating a folder in current workspace using java code

    Hi Experts,
    I need to create a folder and some file in the workspace of NWDS user. Can someone please suggest how can i find out the workspace of user using JAVA code.
    IWorkspaceRoot is not working in NWDS.
    Regards
    Pranav

    Hi Pranav,
    Tell me if you want to create this folder at run time or in NWDS while developing application.
    If you want to create it at the time of development just change your perspective to Java perspective and from there you can see the entire project structure and from there you can create desired files / folders.
    Ninad

  • How to access a file in Unix server from windows using java

    I want to access a file in unix server from windows using java program.
    I have the following code. I am able to open the url in a web browser.
    String urlStr="ftp:user:passwd@unix-server:ftp-port//javatest/test.csv;type=i";
    URL url = new URL(urlStr);
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream)));
    String inputLine;
    while((inputLine=in.readLine()))!=null){
    System.out.println(inputLine);
    in.close();
    I get the following error
    java.io.FileNotFoundException: /javatest/test.csv
    at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnection.java:333)
    at java.net.URL.openStream(URL.java:960)
    at com.test.samples.Test.main(Test.java:45)

    urlStr="ftp:user:passwd@unix-server:ftp-port//javatest/test.csv;type=i";
    I have given the format of the urlStr that I am using in the code. The actiual values are used in my code. I have tried pasting this url in the browser and it opens the file.

  • Read an excel file using java code

    Hi,
    I want to create an excel file on the client machine based on the personal details entered on the web page. And I want to save the file on the client machine in the form of CSV. Then I want to read the contents of the spreadsheet using Java Code from the using servlets. Can I read the contents of the file directly from the client machine or do i need to save the file on the server and then read the contents of it. Please help me solve this.

    Hi,
    I want to create an excel file on the client machine
    based on the personal details entered on the web
    page. And I want to save the file on the client
    machine in the form of CSV. Then I want to read the
    contents of the spreadsheet using Java Code from the
    using servlets. Can I read the contents of the file
    directly from the client machine or do i need to save
    the file on the server and then read the contents of
    it. Please help me solve this.As stated I am rather certain that is impossible.
    Servers don't access the file systems of client machines.

  • How do I produce an excel file using java code

    How do i produce an excel file using java code.
    If it is possible would ne one have ne source code as an example.
    I have tried looking up information on outputing the information to a *.csv file but unfortunality i have had no luck in finding any information. To be exact ne source code.
    Thanks
    Lee

    That's what I use and I'd be the first to admit that it's very messy. But it works. Go use Google and see what else you can find.

  • How to launch Jar file in Mac Os using java code??

    can anyone tell me how can i launch another jar file in my apllication using java code.

    define "launch".
    - You want to run a new java program in a separate process? (see Runtime.exec())
    - You want to run a method in a specific class in the jar? (add jar to application classpath and then simply instantiate the class and call the method)

  • How to compare two huge xml files(50MB+) using Java Code

    I want to compare two huge xml files using java code and need to find the difference of those xml files
    is there any API for that

    You should find third party API

  • How to write excel file (.xlsx) using file adapter without using java code

    Hi All,
    In soa suite 11g Is there any ways to write the data to the excel ( xlsx ) file using fileadapter and not using java code..Thanks in Advance

    Hi Siva,
    I don't think there is any way to write .xls file directly. You'll have to use some Java API (iText etc.) to create an .xls file. However, you can write .csv file that can be easily converted into .xls at the target end. In MS, it opens as Excel file if delimiter is comma *,*.
    Regards,
    Neeraj Sehgal

  • Updating an existing xml file using java code

    hi friends,
    I have simple problem, I have an existing xml file and I want to update some of the values in the file.
    can any one send me the java code for that.
    bye.
    -harish

    org.w3c.dom.Document d = parseXmlFile("D:/www/Detailcache/detail.xml", false);
    public static Document parseXmlFile(String filename, boolean validating) {
    try {
    // Create a builder factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(validating);
    // Create the builder and parse the file
    Document doc = factory.newDocumentBuilder().parse(new File(filename));
    return doc;
    } catch (Exception e) {
    System.out.println("ERROR-->");e.printStackTrace();
    return null;
    look at .. for more related examples
    http://javaalmanac.com/egs/javax.xml.parsers/BasicDom.html?l=rel

  • How to retrieve CPU id in linux using java?

    Hello everyone!!
    I want to retrieve CPU Id from a liux system using java code.
    Please reply with code if possible.
    Thank you in advance.

    Open "/proc/cpuinfo" and parse.

  • How to dynamically configure JPA setting at runtime using java code?

    Hi,
    I am new to EJB 3.0 and JPA. I am trying to help my company to deploy the use of JPA in EJB3.0. Currently, i am trying out with OpenJPA in IBM Webshpere Application Server 7.0. We have four different WAS servers running for testing, system integration testing, user testing and production respectively, and in each region, the configurations for data source, JDBC username and password, schema, etc are different. So i think i would need to configure the JPA setting during runtime using Java code that determines which is the environment. And apparently i am stuck with the limited knowledge i have.
    1) I understand that i could override the JDBC in the persistence xml by creating entity manager using entity manager factory. But is it possible that i do similar thing by using inejction of persistence context on entity manager to obtain a container managed entity manager?
    2) Alternatively, it is possible to create multiple persistence unit in the XML and inject different PU to the entity manager, am i right? But how to inject dynamically since @PersistenceContext(unitName="xxx") only accepts constant declaration.
    3) Is it possible that the JDBC username and password are read from properties file?
    Thanks for your help in advance!

    Hi
    Thanks for the reply.
    Are you saying that i have to configure the data source authentication to the backend DB2 using the JAAS-J2C? Correct me if i am mistaken. I guess i am unable to do so as the application server setup only contains one data source, and the server hosted a number of applications. Every applications has their own JDBC username and password supply to the data source (the ID supplied at the DB2 side will decide which resource can access) and thus, i have to supply the username and password at runtime. Talked to the server guy and seems that it is not feasible to have seperate datasource for each applications as considered to the volume of applications hosted inside the server.
    Any suggestion?

Maybe you are looking for

  • How to access 3rd party website into MS CRM online 2011/2013

    Hi, I want to access a form which is in my .net application/website  into the ms crm 2011/2013 on-line versions using web-services. Actually from .net form using web-service I have added contacts into CRM but now I want to do it in reverse way, like

  • Messages (-1) error - can't send or receive messages

    Haven't been able to send or receive messages since last night. Error shown in link below. Really strange. Don't remember doing anything in particular that might have caused it. http://img217.imageshack.us/img217/6581/photogo.png

  • Dynamic copy operation in BPEL process

    Hi. I wan to create a Copy Operation which would copy a specific part of the input XML depending on what is the name of activity. So for example I have a invoke activity - "thisIsTheActivityName" I want to get the name of the activity - put it in the

  • My iphone is not starting up

    hello there, my iphone has a problem... When i ture it on it has the apple logo in it, but when the loading comes below the iphone the iphone turns itself off and it restarts again. I can not turn it off too, it just keeps on doing it again and agian

  • HT201210 HOW DO YOU REMOVE MUSIC FROM IPHONE?

    How do your remove music tracks/albums from my iphone?