Java Code Examples for com.jcraft.jsch.ChannelSftp#mkdir()

The following examples show how to use com.jcraft.jsch.ChannelSftp#mkdir() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FTPUtil.java    From seed with Apache License 2.0 8 votes vote down vote up
/**
 * 创建远程目录
 * @param remotePath 不含文件名的远程路径(格式为/a/b/c)
 */
private static void createRemoteFolderViaSFTP(ChannelSftp channelSftp, String remotePath){
    String[] folders = remotePath.split("/");
    String remoteTempPath = "";
    for(String folder : folders){
        if(StringUtils.isNotBlank(folder)){
            remoteTempPath += "/" + folder;
            boolean flag = true;
            try{
                channelSftp.cd(remoteTempPath);
            }catch(SftpException e){
                flag = false;
            }
            LogUtil.getLogger().info("change working directory : " + remoteTempPath + "-->" + (flag?"SUCCESS":"FAIL"));
            if(!flag){
                try{
                    channelSftp.mkdir(remoteTempPath);
                    flag = true;
                }catch(SftpException ignored){}
                LogUtil.getLogger().info("make directory : " + remoteTempPath + "-->" + (flag?"SUCCESS":"FAIL"));
            }
        }
    }
}
 
Example 2
Source File: SSHShell.java    From azure-libraries-for-java with MIT License 7 votes vote down vote up
/**
 * Creates a new file on the remote host using the input content.
 *
 * @param from the byte array content to be uploaded
 * @param fileName the name of the file for which the content will be saved into
 * @param toPath the path of the file for which the content will be saved into
 * @param isUserHomeBased true if the path of the file is relative to the user's home directory
 * @param filePerm file permissions to be set
 * @throws Exception exception thrown
 */
public void upload(InputStream from, String fileName, String toPath, boolean isUserHomeBased, String filePerm) throws Exception {
    ChannelSftp channel = (ChannelSftp) this.session.openChannel("sftp");
    channel.connect();
    String absolutePath = isUserHomeBased ? channel.getHome() + "/" + toPath : toPath;

    String path = "";
    for (String dir : absolutePath.split("/")) {
        path = path + "/" + dir;
        try {
            channel.mkdir(path);
        } catch (Exception ee) {
        }
    }
    channel.cd(absolutePath);
    channel.put(from, fileName);
    if (filePerm != null) {
        channel.chmod(Integer.parseInt(filePerm), absolutePath + "/" + fileName);
    }

    channel.disconnect();
}
 
Example 3
Source File: SFTPUtil.java    From bestconf with Apache License 2.0 6 votes vote down vote up
public static void upload(String directory, String uploadFile, ChannelSftp sftp) throws Exception{
	
	File file = new File(uploadFile);
	if(file.exists()){
		
		try {
			Vector content = sftp.ls(directory);
			if(content == null){
				sftp.mkdir(directory);
				System.out.println("mkdir:" + directory);
			}
		} catch (SftpException e) {
			sftp.mkdir(directory);
		}
		sftp.cd(directory);
		System.out.println("directory: " + directory);
		if(file.isFile()){
			InputStream ins = new FileInputStream(file);
			
			sftp.put(ins, new String(file.getName().getBytes(),"UTF-8"));
			
		}else{
			File[] files = file.listFiles();
			for (File file2 : files) {
				String dir = file2.getAbsolutePath();
				if(file2.isDirectory()){
					String str = dir.substring(dir.lastIndexOf(file2.separator));
					directory = directory + str;
				}
				System.out.println("directory is :" + directory);
				upload(directory,dir,sftp);
			}
		}
	}
}
 
Example 4
Source File: SftpBuildProcessAdapter.java    From teamcity-deployer-plugin with Apache License 2.0 6 votes vote down vote up
private void createRemotePath(@NotNull final ChannelSftp channel,
                              @NotNull final String destination) throws SftpException {
  final int endIndex = destination.lastIndexOf('/');
  if (endIndex > 0) {
    createRemotePath(channel, destination.substring(0, endIndex));
  }
  try {
    channel.stat(destination);
  } catch (SftpException e) {
    // dir does not exist.
    if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
      channel.mkdir(destination);
    }
  }

}
 
Example 5
Source File: JobEntrySFTPIT.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private void uploadFile( String dir, String file ) throws Exception {
  Session session = server.createJschSession();
  session.connect();
  try {
    ChannelSftp sftp = (ChannelSftp) session.openChannel( "sftp" );
    sftp.connect();
    try {
      sftp.mkdir( dir );
      sftp.cd( dir );
      sftp.put( new ByteArrayInputStream( "data".getBytes() ), file );
    } finally {
      sftp.disconnect();
    }
  } finally {
    session.disconnect();
  }
}
 
Example 6
Source File: JSchSshSession.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private void mkdirs(ChannelSftp chan, String dir) throws SftpException {
  StringBuilder pathBuilder = new StringBuilder(dir.length());
  for (String part : Splitter.on('/').omitEmptyStrings().split(dir)) {
    pathBuilder.append(part);
    chan.mkdir(pathBuilder.toString());
    pathBuilder.append('/');
  }
}
 
Example 7
Source File: SFTPRepository.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
private void mkdirs(String directory, ChannelSftp c) throws SftpException {
    try {
        SftpATTRS att = c.stat(directory);
        if (att != null && att.isDir()) {
            return;
        }
    } catch (SftpException ex) {
        if (directory.indexOf('/') != -1) {
            mkdirs(directory.substring(0, directory.lastIndexOf('/')), c);
        }
        c.mkdir(directory);
    }
}
 
Example 8
Source File: JobConfigUtil.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create directory in remote machine using sftp
 * @param sftp
 * @param file file (even though it is a remote path)
 * @throws SftpException
 */
private static void createPathInRemote(ChannelSftp sftp, File file) throws SftpException {
	if (file.getAbsolutePath().equals("/")) {
		return;
	}
	if (file.getParentFile() != null) {
		createPathInRemote(sftp, file.getParentFile());
	}
	LOGGER.debug("Creating directory [" + file.getAbsolutePath() + "] on server");
	try {
		sftp.mkdir(file.getAbsolutePath());
	} catch (SftpException e) {
		LOGGER.debug("Unable to create directory [" + file.getAbsolutePath() + "] on server.");
	}
}
 
Example 9
Source File: SFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void create(ChannelSftp channel, URI uri, CreateParameters params) throws IOException, SftpException {
	if (Thread.currentThread().isInterrupted()) {
		throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$
	}
	boolean createDirectory = Boolean.TRUE.equals(params.isDirectory());
	boolean createParents = Boolean.TRUE.equals(params.isMakeParents());
	Info fileInfo = info(uri, channel);
	String path = getPath(uri);
	Date lastModified = params.getLastModified();
	if (fileInfo == null) { // does not exist
		if (createParents) {
			URI parentUri = URIUtils.getParentURI(uri);
			create(channel, parentUri, params.clone().setDirectory(true));
		}
		if (createDirectory) {
			channel.mkdir(path);
		} else {
			createFile(channel, path);
		}
		if (lastModified != null) {
			setLastModified(channel, path, lastModified.getTime());
		}
	} else {
		if (createDirectory != fileInfo.isDirectory()) {
			throw new IOException(MessageFormat.format(createDirectory ? FileOperationMessages.getString("IOperationHandler.exists_not_directory") : FileOperationMessages.getString("IOperationHandler.exists_not_file"), uri)); //$NON-NLS-1$ //$NON-NLS-2$
		}
		setLastModified(channel, path, lastModified != null ? lastModified.getTime() : System.currentTimeMillis());
	}
}
 
Example 10
Source File: PooledSFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void create(ChannelSftp channel, URI uri, CreateParameters params) throws IOException, SftpException {
	if (Thread.currentThread().isInterrupted()) {
		throw new IOException(FileOperationMessages.getString("IOperationHandler.interrupted")); //$NON-NLS-1$
	}
	boolean createDirectory = Boolean.TRUE.equals(params.isDirectory());
	boolean createParents = Boolean.TRUE.equals(params.isMakeParents());
	Info fileInfo = simpleInfo(uri, channel);
	String path = getPath(uri);
	Date lastModified = params.getLastModified();
	if (fileInfo == null) { // does not exist
		URI parentUri = URIUtils.getParentURI(uri);
		if (createParents) {
			create(channel, parentUri, params.clone().setDirectory(true));
		} else if (parentUri != null) {
			if (simpleInfo(parentUri, channel) == null) {
				throw new FileNotFoundException("No such directory: " + parentUri);
			}
		}
		if (createDirectory) {
			channel.mkdir(path);
		} else {
			createFile(channel, path);
		}
		if (lastModified != null) {
			setLastModified(channel, path, lastModified.getTime(), createDirectory);
		}
	} else {
		if (createDirectory != fileInfo.isDirectory()) {
			throw new IOException(MessageFormat.format(createDirectory ? FileOperationMessages.getString("IOperationHandler.exists_not_directory") : FileOperationMessages.getString("IOperationHandler.exists_not_file"), uri)); //$NON-NLS-1$ //$NON-NLS-2$
		}
		setLastModified(channel, path, (lastModified != null) ? lastModified.getTime() : System.currentTimeMillis(), fileInfo.isDirectory());
	}
}
 
Example 11
Source File: SftpLightWeightFileSystem.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean mkdirs(Path path, FsPermission permission) throws IOException {
  ChannelSftp channel = null;
  try {
    channel = this.fsHelper.getSftpChannel();
    channel.mkdir(HadoopUtils.toUriPath(path));
    channel.chmod(permission.toShort(), HadoopUtils.toUriPath(path));
  } catch (SftpException e) {
    throw new IOException(e);
  } finally {
    safeDisconnect(channel);
  }
  return true;
}
 
Example 12
Source File: SftpFileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Creates this file as a folder.
 */
@Override
protected void doCreateFolder() throws Exception {
    final ChannelSftp channel = getAbstractFileSystem().getChannel();
    try {
        channel.mkdir(relPath);
    } finally {
        getAbstractFileSystem().putChannel(channel);
    }
}