2011-07-19 37 views
2

的另一個位置讀取一個文件下面是我的代碼讀取使用JSch使用JSch

import com.jcraft.jsch.*; 
import java.io.BufferedReader; 
import java.io.*; 
import java.util.Vector; 

public class SftpClient { 
    public static void main(String args[]) { 
     JSch jsch = new JSch(); 
     Session session = null; 
     FileReader reader =null; 
     BufferedReader buffer = null; 
     try 
     { 
. 
      session = jsch.getSession("userName", "Ip Address"); 
      java.util.Properties config = new java.util.Properties(); 
      config.put("StrictHostKeyChecking", "no"); 
      session.setConfig(config); 
      session.setPassword("password");     
      session.connect();    
      Channel channel = session.openChannel("sftp"); 
      channel.connect(); 
      ChannelSftp sftpChannel = (ChannelSftp) channel; 
      System.out.println("Is connected to IP:"+channel.isConnected()); 
      Vector ls=sftpChannel.ls("/misc/downloads/"); 
      for(int i=0;i<ls.size();i++){ 
       System.out.println("Ls:"+ls.get(i)); 
      } 
      sftpChannel.cd("/misc/downloads/");    
      File file = new File("Text.txt"); 
      sftpChannel.put(new FileInputStream(file),"Text.txt");    
      reader = new FileReader(file); 
      buffer = new BufferedReader(reader);     
      String getLine = ""; 
      while ((getLine = buffer.readLine())!=null) 
      { 
       System.out.println("Line: "+getLine); 
      } 
      sftpChannel.exit();    
      session.disconnect(); 
     } 
     catch (JSchException e) { 
      e.printStackTrace(); 
     } 
     catch (Exception e){ 
      e.printStackTrace(); 
     } 
     finally{ 
      try{ 
       if(reader!=null) 
        reader.close(); 
       if(buffer!=null) 
        buffer.close(); 
      } 
      catch(Exception e){ 
       System.out.println("Exception:"+e); 
      } 
     } 
    } 

}代碼的

輸出從另一個位置的文件是:

Is connected to IP:true 
Ls:-rw-r--r-- 1 root  root   733 Jul 19 17:46 Text.txt 
java.io.FileNotFoundException: Text.txt (The system cannot find the file specified) 
    at java.io.FileInputStream.open(Native Method) 
    at java.io.FileInputStream.<init>(FileInputStream.java:103) 
    at SftpClient.main(SftpClient.java:34) 

我得到FileNotFoundException,但在此之前,我讓SOP使用ls列出/ misc/downloads /路徑中的所有文件。

我能做些什麼來解決這個問題?

回答

3

FileInputStream,嘗試從您的本地文件系統讀取文件(其中不存在),但在我看來,你真的想從遠程文件系統讀取它。還是你想下載到本地系統,然後從那裏讀取?

無論如何,要從遠程端下載,請使用ChannelSftp而不是put(用於上傳)的get方法之一。

1

您可以考慮使用Apache VFS來讀取遠程文件。它簡單而強大的庫。