I have a application that runs as a schedule.It connect to ftp server and get files from remote folder.scheduler runs in every 5min time.Sometimes when there are lot of files in remote location, scheduler runs again while first cycle is running.In such situation some times it download 0 size files even actual file size is greater than 0 in remote location.Does anyone have any idea why this happen?
below is the code to import files.
private void importEDIFiles(String host, String user, String password, String path, String road) {
try {
String edi824Path = path + "/" + EDI_824_FOLDER;
FTPBroker ftpBroker = new FTPBroker(host, user, password, edi824Path);
FTPClient client = ftpBroker.makeFTPConeection();
String os = client.getSystemName();
client.setFileTransferMode(FTP.ASCII_FILE_TYPE);
File edi824File = null;
File edi824Filebak = null;
ArrayList<FTPFile> files;
try {
FTPFile[] ftpfiles = client.listFiles();
logger.info("\t" + ftpfiles.length + " files are in ftp location ");
if (ftpfiles.length > 0) {
files = removeZeroFiles(ftpfiles);
for(int x=0;x<files.size();x++){
logger.info("name ---"+files.get(x).getName());
logger.info("size ----"+files.get(x).getSize());
}
String ftpFile = null;
logger.info("\t" + files.size() + " downloading from " + road + " rail road.");
for (int i = 0; i < files.size(); i++) {
ftpFile = files.get(i).getName();
logger.info("\t" + ftpFile + " is downloading....");
// logger.info("\t" + ftpFile + " size ...." + ftpFile.isEmpty());
String source = destinationFilePath + pathSeparator + road + pathSeparator + ftpFile;
String target = edi_824backupFilePath + pathSeparator + road + pathSeparator + ftpFile;
edi824File = new File(source);
edi824Filebak = new File(target);
FileOutputStream fosout = new FileOutputStream(source);
boolean isRetrieved = client.retrieveFile(ftpFile, fosout);
logger.debug("isRetrieved : " + isRetrieved);
FileUtils.copyFile(edi824File,edi824Filebak);
fosout.flush();
fosout.close();
boolean isDelete = client.deleteFile(ftpFile);
logger.debug("isDelete : " + isDelete);
}
} else {
logger.info("No files to Pull in the FTP Location for " + user);
//throw new RuntimeException("No files to Pull in FTP Location.");
}
} catch (Exception e) {
logger.error(e,e);
e.printStackTrace();
} finally {
client.logout();
client.disconnect();
}
} catch (Exception ex) {
logger.error(ex, ex);
ex.printStackTrace();
}
}
you can use a flag boolean isRunning(), setRunning(boolean ), and synchronize your code so that two or more threads would not run the same method at the same time
Related
I am making an application for file uploading in Java using jSch. I want to put my file in different directories based on their creation date etc.
I have a main directory "/var/local/recordingsbackup/" in which I am creating other directories and putting data in them.
To achieve this:
I have to create Dir'y like
"/var/local/recordingsbackup/20140207/root/SUCCESS/WN/" and put
data in it.
I've tried this so far:
private void fileTransfer(ChannelSftp channelTarget, temp_recording_log recObj, String filePath) {
int fileNameStartIndex = filePath.lastIndexOf("/") + 1;
String date = new SimpleDateFormat("yyyyMMdd").format(recObj.getCalldate());
String fileName = filePath.substring(fileNameStartIndex);
String staticPath = "/var/local/recordingsbackup/";
String completeBackupPath = staticPath + date + "/" + recObj.getUsername() + "/" + recObj.getStatus() + "/" + recObj.getDisposition() + "/";
try {
InputStream get = SourceChannel.get(filePath);
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
channelTarget.mkdir(completeBackupPath); // error on this line
channelTarget.put(get, completeBackupPath + fileName);
}
} catch (SftpException e) {
log.error("Error Occured ======== File or Directory dosen't exists === " + filePath);
e.printStackTrace();
}
}
If I'm creating single dir like /var/local/recordingsbackup/ then no error occurs and files successfully uploaded.
Please help me in this...how can I create these Nested Directories???
Finally, I've done it.
This is how I got succeed :
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
String[] complPath = completeBackupPath.split("/");
channelTarget.cd("/");
for (String dir : complPath) {
if (folder.length() > 0) {
try {
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.cd(folder);
} catch (SftpException e2) {
channelTarget.mkdir(folder);
channelTarget.cd(folder);
}
}
}
channelTarget.cd("/");
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.put(get, completeBackupPath + fileName);
}
I don't think what you want to do is possible in the SFTP protocol. You will have to create each sub-directory in turn.
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
ch.mkdir(fullPath + folders[i]);
}
fullPath = fullPath + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
I used this implementation to create nested folders.
I tried not to use Exception. Keep in mind that filesystem is linux based.
The OP already found a solution but I wanted to append to it.
Simply I do mkdir if the folder that I wanted to create doesn't exist in "ls" result.
Correction of the previous script:
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
// Add separator path
ch.mkdir(fullPath + "/" + folders[i]);
}
// Add separator path
fullPath = fullPath + "/" + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
Another solution is execute shell command:
String remotePath = "fake/folders/recursive/on/sftp/server";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
// NOTE: the provided paths are expected to require no escaping
channel.setCommand("mkdir -p " + remotePath);
channel.connect();
while (!channel.isClosed()) {
// dir creation is usually fast, so only wait for a short time
Thread.sleep(SHORT_WAIT_MSEC);
}
channel.disconnect();
if (channel.getExitStatus() != 0) {
throw new IOException("Creating directory failed: " + remotePath);
}
I am making an application for file uploading in Java using jSch. I want to put my file in different directories based on their creation date etc.
I have a main directory "/var/local/recordingsbackup/" in which I am creating other directories and putting data in them.
To achieve this:
I have to create Dir'y like
"/var/local/recordingsbackup/20140207/root/SUCCESS/WN/" and put
data in it.
I've tried this so far:
private void fileTransfer(ChannelSftp channelTarget, temp_recording_log recObj, String filePath) {
int fileNameStartIndex = filePath.lastIndexOf("/") + 1;
String date = new SimpleDateFormat("yyyyMMdd").format(recObj.getCalldate());
String fileName = filePath.substring(fileNameStartIndex);
String staticPath = "/var/local/recordingsbackup/";
String completeBackupPath = staticPath + date + "/" + recObj.getUsername() + "/" + recObj.getStatus() + "/" + recObj.getDisposition() + "/";
try {
InputStream get = SourceChannel.get(filePath);
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
channelTarget.mkdir(completeBackupPath); // error on this line
channelTarget.put(get, completeBackupPath + fileName);
}
} catch (SftpException e) {
log.error("Error Occured ======== File or Directory dosen't exists === " + filePath);
e.printStackTrace();
}
}
If I'm creating single dir like /var/local/recordingsbackup/ then no error occurs and files successfully uploaded.
Please help me in this...how can I create these Nested Directories???
Finally, I've done it.
This is how I got succeed :
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
String[] complPath = completeBackupPath.split("/");
channelTarget.cd("/");
for (String dir : complPath) {
if (folder.length() > 0) {
try {
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.cd(folder);
} catch (SftpException e2) {
channelTarget.mkdir(folder);
channelTarget.cd(folder);
}
}
}
channelTarget.cd("/");
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.put(get, completeBackupPath + fileName);
}
I don't think what you want to do is possible in the SFTP protocol. You will have to create each sub-directory in turn.
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
ch.mkdir(fullPath + folders[i]);
}
fullPath = fullPath + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
I used this implementation to create nested folders.
I tried not to use Exception. Keep in mind that filesystem is linux based.
The OP already found a solution but I wanted to append to it.
Simply I do mkdir if the folder that I wanted to create doesn't exist in "ls" result.
Correction of the previous script:
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
// Add separator path
ch.mkdir(fullPath + "/" + folders[i]);
}
// Add separator path
fullPath = fullPath + "/" + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
Another solution is execute shell command:
String remotePath = "fake/folders/recursive/on/sftp/server";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
// NOTE: the provided paths are expected to require no escaping
channel.setCommand("mkdir -p " + remotePath);
channel.connect();
while (!channel.isClosed()) {
// dir creation is usually fast, so only wait for a short time
Thread.sleep(SHORT_WAIT_MSEC);
}
channel.disconnect();
if (channel.getExitStatus() != 0) {
throw new IOException("Creating directory failed: " + remotePath);
}
public String generateDataPDF() {
System.out.println("Inside generate PDF");
String filePath = "";
HttpSession sess = ServletActionContext.getRequest().getSession();
try {
sess.setAttribute("msg", "");
if (getCrnListType().equalsIgnoreCase("F")) {
try {
filePath = getModulePath("CRNLIST_BASE_LOCATION") + File.separator + getCrnFileFileName();
System.out.println("File stored path : " + filePath);
target = new File(filePath);
FileUtils.copyFile(crnFile, target);
} catch (Exception e) {
System.out.println("File path Exception " + e);
}
}
System.out.println("Values from jsp are : 1)Mode of Generation : " + getCrnListType() + " 2)Policy Number : " + getCrnNumber() + " 3)Uploaded File Name : " + getCrnFileFileName() + " 4)LogoType : " + getLogoType()
+ " 5)Output Path : " + getOutputPath() + " 6)Type of Generation : " + getOptionId() + " 7)PDF Name : " + getPdfName());
String srtVAL = "";
String arrayVaue[] = new String[]{getCrnListType(), getCrnListType().equalsIgnoreCase("S") ? getCrnNumber() : filePath, getLogoType().equalsIgnoreCase("WL") ? "0" : "1",
getOutputPath(), getGenMode(), getRenType()};
//INS DB Connection
con = getInsjdbcConnection();
ArrayList selectedCRNList = new ArrayList();
String selectedCRNStr = "";
selectedCRNStr = getSelectedVal(selectedCRNStr, arrayVaue[1]);
String[] fileRes = selectedCRNStr.split("\\,");
if (fileRes[0].equalsIgnoreCase("FAIL")) {
System.out.println("fileRes is FAIL beacause of other extension file.");
sess.setAttribute("pr", "Please upload xls or csv file.");
return SUCCESS;
}
System.out.println("List file is : " + selectedCRNStr);
String st[] = srtVAL.split("[*]");
String billDateStr = DateUtil.getStrDateProc(new Date());
Timestamp strtPasrsingTm = new Timestamp(new Date().getTime());
String minAMPM = DateUtil.getTimeDate(new Date());
String str = "";
String batchID = callSequence();
try {
System.out.println("Inside Multiple policy Generation.");
String userName=sess.getAttribute("loginName").toString();
String list = getProcessesdList(userName);
if (list != null) {
System.out.println("list is not null Users previous data is processing.....");
//setTotalPDFgNERATEDmSG("Data is processing please wait.");
sess.setAttribute("pr","Batch Id "+list+" for User " + userName + " is currently running.Please wait till this Process complete.");
return SUCCESS;
}
String[] policyNo = selectedCRNStr.split("\\,");
int l = 0, f = 0,counter=1;
for (int j = 0; j < policyNo.length; j++,counter++) {
String pdfFileName = "";
int uniqueId=counter;
globUniqueId=uniqueId;
insertData(batchID, new Date(), policyNo[j], getOptionId(), userName,uniqueId);
System.out.println("Executing Proc one by one.");
System.out.println("policyNo[j]" + policyNo[j]);
System.out.println("getOptionId()" + getOptionId());
System.out.println("seqValue i.e batchId : " + batchID);
}
str = callProcedure(policyNo[j], getOptionId(), batchID);
String[] procResponse = str.split("\\|");
for (int i = 0; i < procResponse.length; i++) {
System.out.println("Response is : " + procResponse[i]);
}
if (procResponse[0].equals("SUCCESS")) {
Generator gen = new Generator();
if (getPdfName().equalsIgnoreCase("true")) {
System.out.println("Checkbox is click i.e true");
pdfFileName = procResponse[1];
} else {
System.out.println("Checkbox is not click i.e false");
String POLICY_SCH_GEN_PSS = getDetailsForFileName(userName, policyNo[j], batchID);
String[] fileName = POLICY_SCH_GEN_PSS.split("\\|");
if (getLogoType().equals("0") || getLogoType().equals("2")) {
System.out.println("If logo is O or 1");
pdfFileName = fileName[1];
} else if (getLogoType().equals("1")) {
System.out.println("If logo is 2");
pdfFileName = fileName[0];
}
}
b1 = gen.genStmt(procResponse[1], procResponse[2], "2", getLogoType(), "0", pdfFileName,"1",userName,batchID);
l++;
updateData(uniqueId,batchID, "Y");
} else {
f++;
updateData(uniqueId,batchID, "F");
}
}
sess.setAttribute("pr","Total "+l+" "+getGenericModulePath("PDF_RES1") + " " + " " + getGenericModulePath("PDF_RES2") + " " + f);
}catch (Exception e) {
updateData(globUniqueId,batchID, "F");
System.out.println("Exception in procedure call");
setTotalPDFgNERATEDmSG("Fail");
e.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
}catch (Exception ex) {
ex.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
System.out.println("Above second return");
return SUCCESS;
}
GenerateDataPDf method generates PDF based on the parameters i.e ProductType(GenMode),CrnList(uploaded in excel file...)Code works fine when only single user generates PDF. But If two different User(User and roles are assigned in application) start the process same time request paraeters are overridden then! Suppose first user request pdf for 50 customers for product 1. User1's process is still running and second user request for product2. Now User1's pdf are generated but for product2.....! Here batchId is unique for every single request.One table is maintained where batch_id,all pdf,generation flags are mainained there. How do I solve this?
As per your comment, this is what I would do, It's probably not the best way to do !
Firstly : Create a function to collet all your data at the beginning. You should not modify/update/create anything when you are generating a PDF. IE : array/list collectPDFData() wich should retourn an array/list.
Secondly : Use a synchronized methods like synchronized boolean generatePDF(array/list)
"Synchronized" methods use monitor lock or intrinsic lock in order to manage synchronization so when using synchronized, each method share the same monitor of the corresponding object.
NB : If you use Synchronize, it's probably useless to collect all your data in a separate way, but I think it's a good practice to make small function dedicated to a specific task.
Thus, your code should be refactored a little bit.
I want to find the count of files inside the svn. i know how to check is it a file or directory.
try {
nodeKind = repository.checkPath("", -1);
} catch (SVNException ex) {
Logger.getLogger(Reassignscreen.class.getName()).log(Level.SEVERE, null, ex);
}
if (nodeKind == SVNNodeKind.NONE) {
System.err.println("There is no entry at '" + url + "'.");
commitClient.doMkDir(new SVNURL[]{SVNURL.parseURIDecoded(url)}, "New Folder");
}
Like this is there any way to retrieve the count of files inside the svn.
Use this code it will help you,
public class DisplayRepositoryList{
static int xmlfilecount = 0;
static ArrayList<String> imagefoldercheck = new ArrayList<String>();
public static void displayrepositorytree(String url, String name, String password) {
xmlfilecount =0;
SVNSetupLibrary.setupLibrary();
SVNRepository repository = null;
try {
repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
} catch (SVNException svne) {
System.err.println("error while creating an SVNRepository for location '" + url + "': " + svne.getMessage());
// System.exit(1);
}
ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(name, password);
repository.setAuthenticationManager(authManager);
try {
SVNNodeKind nodeKind = repository.checkPath("", -1);
if (nodeKind == SVNNodeKind.NONE) {
System.err.println("There is no entry at '" + url + "'.");
// System.exit(1);
} else if (nodeKind == SVNNodeKind.FILE) {
System.err.println("The entry at '" + url + "' is a file while a directory was expected.");
// System.exit(1);
}
System.out.println("Repository Root: " + repository.getRepositoryRoot(true));
System.out.println("Repository UUID: " + repository.getRepositoryUUID(true));
System.out.println("");
imagefoldercheck = new ArrayList<String>();
listEntries(repository, "");
} catch (SVNException svne) {
System.err.println("error while listing entries: "
+ svne.getMessage());
}
/*
* Gets the latest revision number of the repository
*/
long latestRevision = -1;
try {
latestRevision = repository.getLatestRevision();
} catch (SVNException svne) {
System.err.println("error while fetching the latest repository revision: "
+ svne.getMessage());
// System.exit(1);
}
System.out.println("");
System.out.println("---------------------------------------------");
System.out.println("Repository latest revision: " + latestRevision);
}
/*
* Initializes the library to work with a repository via
* different protocols.
*/
public static void listEntries(SVNRepository repository, String path)
throws SVNException {
Collection entries = repository.getDir(path, -1, null,
(Collection) null);
Iterator iterator = entries.iterator();
while (iterator.hasNext()) {
SVNDirEntry entry = (SVNDirEntry) iterator.next();
if (entry.getName().endsWith(".xml")) {
System.out.println(entry.getName() + " " + xmlfilecount);
xmlfilecount = xmlfilecount + 1;
imagefoldercheck.add(entry.getName());
}
System.out.println("imagefoldercheck --> "+imagefoldercheck);
/*
* Checking up if the entry is a directory.
*/
if (entry.getKind() == SVNNodeKind.DIR) {
listEntries(repository, (path.equals("")) ? entry.getName()
: path + "/" + entry.getName());
}
}
}
}
I am making an application for file uploading in Java using jSch. I want to put my file in different directories based on their creation date etc.
I have a main directory "/var/local/recordingsbackup/" in which I am creating other directories and putting data in them.
To achieve this:
I have to create Dir'y like
"/var/local/recordingsbackup/20140207/root/SUCCESS/WN/" and put
data in it.
I've tried this so far:
private void fileTransfer(ChannelSftp channelTarget, temp_recording_log recObj, String filePath) {
int fileNameStartIndex = filePath.lastIndexOf("/") + 1;
String date = new SimpleDateFormat("yyyyMMdd").format(recObj.getCalldate());
String fileName = filePath.substring(fileNameStartIndex);
String staticPath = "/var/local/recordingsbackup/";
String completeBackupPath = staticPath + date + "/" + recObj.getUsername() + "/" + recObj.getStatus() + "/" + recObj.getDisposition() + "/";
try {
InputStream get = SourceChannel.get(filePath);
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
channelTarget.mkdir(completeBackupPath); // error on this line
channelTarget.put(get, completeBackupPath + fileName);
}
} catch (SftpException e) {
log.error("Error Occured ======== File or Directory dosen't exists === " + filePath);
e.printStackTrace();
}
}
If I'm creating single dir like /var/local/recordingsbackup/ then no error occurs and files successfully uploaded.
Please help me in this...how can I create these Nested Directories???
Finally, I've done it.
This is how I got succeed :
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
String[] complPath = completeBackupPath.split("/");
channelTarget.cd("/");
for (String dir : complPath) {
if (folder.length() > 0) {
try {
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.cd(folder);
} catch (SftpException e2) {
channelTarget.mkdir(folder);
channelTarget.cd(folder);
}
}
}
channelTarget.cd("/");
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.put(get, completeBackupPath + fileName);
}
I don't think what you want to do is possible in the SFTP protocol. You will have to create each sub-directory in turn.
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
ch.mkdir(fullPath + folders[i]);
}
fullPath = fullPath + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
I used this implementation to create nested folders.
I tried not to use Exception. Keep in mind that filesystem is linux based.
The OP already found a solution but I wanted to append to it.
Simply I do mkdir if the folder that I wanted to create doesn't exist in "ls" result.
Correction of the previous script:
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
// Add separator path
ch.mkdir(fullPath + "/" + folders[i]);
}
// Add separator path
fullPath = fullPath + "/" + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
Another solution is execute shell command:
String remotePath = "fake/folders/recursive/on/sftp/server";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
// NOTE: the provided paths are expected to require no escaping
channel.setCommand("mkdir -p " + remotePath);
channel.connect();
while (!channel.isClosed()) {
// dir creation is usually fast, so only wait for a short time
Thread.sleep(SHORT_WAIT_MSEC);
}
channel.disconnect();
if (channel.getExitStatus() != 0) {
throw new IOException("Creating directory failed: " + remotePath);
}