2

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 が発生していますが、その前に、ls を使用して /misc/downloads/ パス内のすべてのファイルを一覧表示する SOP を作成しました。

この問題を解決するにはどうすればよいですか?

4

2 に答える 2

3

ローカルファイル システム (ファイルが存在しない場所)FileInputStreamからファイルを読み込もうとしますが、実際にはリモート ファイル システムから読み込もうとしているように見えます。それとも、ローカル システムにダウンロードして、そこから読み取りますか?

とにかく、リモート側からダウンロードするには、(アップロード用ではありません)のいずれかのget方法を使用します。ChannelSftpput

于 2011-07-19T21:34:30.503 に答える
1

リモートファイルの読み取りにApache VFSの使用を検討できます。シンプルで強力なライブラリです。

于 2011-07-19T13:52:32.140 に答える