Skip to content

gerardnico/niofs-sftp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NIOFS Sftp

Introduction

Provides access to the files on an SFTP server (that is, an SSH or SCP server).

Get an absolute path with a absolute URI Format

The below URI is absolute because it specifies a scheme:

sftp://[ username[: password]@] hostname[: port][ /absolute/path ]

where:

  • User and password must be encoded as it's an URI format.
  • Path is always absolute with a scheme. It must then begin with a /

With Paths:

URI uri = URI.create("sftp://myusername:mypassword@somehost:2222/tmp");
Path myPath = Paths.get(uri);

// And don't forget to close the file system when you don't need it anymore
myPath.getFileSystem().close();

The id of a sftp file system is the combination of user, host, port and working directory. Then if you need a second file from the same file system, you can omit the password. Example:

URI uri = URI.create("sftp://myusername@somehost:2222/my/Other/Absolute/Path");
Path mySecondPath = Paths.get(uri);

You can also just ask the file system from the first path myPath and then create a new path (even a relative one). Example:

Path mySecondPath = myPath.getFileSystem().getPath("myRelativePath");

Get the Sftp File System

  • Through the installed provider
for (FileSystemProvider fileSystemProvider : FileSystemProvider.installedProviders()) {
   if (SftpFileSystemProvider.SFTP_SCHEME.equals(fileSystemProvider.getScheme())) {
       sftpFileSystemProvider = fileSystemProvider;
   }
}
  • With a path
FileSystem sftpFileSystem = Paths.get(URI.create("sftp:/")).getFileSystem();

Don't forget to close it when it's no more needed.

sftpFileSystem.close();

Get a relative path from a Working Directory

During the instantiation of the file system, you can set the working directory. When not defined, the working directory default normally to the user's home directory.

URI uri = new URI("sftp://" + user + ":" + pwd + "@" + host + ":" + port);
Map<String, String> env = new HashMap<>();
env.put("working.directory","/myWorkingDirectory");

FileSystem sftpFileSystem = FileSystemProvider.newFileSystem(uri, env);
Path path = sftpFileSystem.getPath("myRelativePath"); 

Implementation

  • Operating System: Actually, only a Linux/Solaris/Unix Server is supported (ie the root begins with "/").
  • The file system is not fully developed and tested against concurrency.

Installation

The jar file must be in the classpath as NIO uses the system class loader to find installed providers.

About

A Java Nio SFTP FileSystem implementation

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages