2013-02-27 39 views
16

Đây là mã của tôi, mã truy xuất nội dung của tệp, trên máy chủ từ xa và hiển thị dưới dạng đầu ra.Chuyển tệp SFTP bằng cách sử dụng Java JSch

package sshexample; 

import com.jcraft.jsch.*; 
import java.io.*; 

public class SSHexample 
{ 
public static void main(String[] args) 
{ 
    String user = "user"; 
    String password = "password"; 
    String host = "192.168.100.103"; 
    int port=22; 

    String remoteFile="sample.txt"; 

    try 
    { 
     JSch jsch = new JSch(); 
     Session session = jsch.getSession(user, host, port); 
     session.setPassword(password); 
     session.setConfig("StrictHostKeyChecking", "no"); 
     System.out.println("Establishing Connection..."); 
     session.connect(); 
     System.out.println("Connection established."); 
     System.out.println("Creating SFTP Channel."); 
     ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp"); 
     sftpChannel.connect(); 
     System.out.println("SFTP Channel created."); 
     InputStream out= null; 
     out= sftpChannel.get(remoteFile); 
     BufferedReader br = new BufferedReader(new InputStreamReader(out)); 
     String line; 
     while ((line = br.readLine()) != null) 
     { 
      System.out.println(line); 
     } 
     br.close(); 
     sftpChannel.disconnect(); 
     session.disconnect(); 
    } 
    catch(JSchException | SftpException | IOException e) 
    { 
     System.out.println(e); 
    } 
} 
} 

Làm cách nào để triển khai chương trình này tệp được sao chép trong máy chủ cục bộ và cách sao chép tệp từ máy chủ cục bộ sang máy chủ.

Dưới đây là cách thực hiện chuyển tệp cho bất kỳ định dạng tệp nào.

+0

Tôi đã cung cấp ví dụ về cách thực hiện điều này từ máy chủ cục bộ đến một phiên bản AWS EC2 từ xa tại đây http://stackoverflow.com/a/16626635/311525 – Scott

+0

Nếu bạn đang tìm kiếm truyền tệp giữa máy chủ cục bộ và từ xa, các liên kết này sẽ hữu ích - [tải lên tệp] (http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/), [tải xuống tệp] (http://kodehelp.com/ java-program-for-download-file-from-sftp-server /) –

Trả lời

2

Cách tầm thường nhất để tải lên một tập tin qua SFTP với JSch là:

JSch jsch = new JSch(); 
Session session = jsch.getSession(user, host); 
session.setPassword(password); 
session.connect(); 

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp"); 
sftpChannel.connect(); 

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip"); 

Tương tự như vậy cho một tải về:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip"); 

Bạn có thể cần phải deal with UnknownHostKey exception.

Các vấn đề liên quan