Example #1
0
  public String getFileContent(String fileName) throws Exception {
    FileSystemManager fsManager = null;
    FileObject sftpFile = null;
    FileObject src = null; // used for cleanup in release()
    String fileContent = null;

    try {
      System.out.println("SFTP download");
      FileSystemOptions opts = null;
      // app.initialize();
      try {
        fsManager = VFS.getManager();
      } catch (FileSystemException ex) {
        throw new RuntimeException("failed to get fsManager from VFS", ex);
      }

      UserAuthenticator auth = new StaticUserAuthenticator(null, this.user, this.password);
      opts = new FileSystemOptions();
      try {
        DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
      } catch (FileSystemException ex) {
        throw new RuntimeException("setUserAuthenticator failed", ex);
      }

      // app.process();
      String startPath =
          "sftp://"
              + this.user
              + ":"
              + this.password
              + "@"
              + this.host
              + ":22"
              + this.remoteDir
              + fileName;

      // Set starting path on remote SFTP server.
      try {
        sftpFile = fsManager.resolveFile(startPath, opts);

        System.out.println("SFTP connection successfully established to " + startPath);
      } catch (FileSystemException ex) {
        throw new RuntimeException("SFTP error parsing path " + this.remoteDir, ex);
      }

      if (sftpFile.exists()) {
        FileContent fc = sftpFile.getContent();
        StringWriter writer = new StringWriter();
        IOUtils.copy(fc.getInputStream(), writer, encoding);
        String theString = writer.toString();
        //	         	System.out.println(theString);
        fileContent = theString;
      }

    } finally {
      // app.release();
      /** Release system resources, close connection to the filesystem. */
      try {
        FileSystem fs = null;
        if (sftpFile != null) {
          fs = sftpFile.getFileSystem(); // This works even if the src is closed.
          fsManager.closeFileSystem(fs);
        } // TODO if sftpFile != null
      } catch (Exception e) {
        System.out.println(e);
      }
    }
    return fileContent;
  }