gpt4 book ai didi

java - 使用 JSch 从另一个位置读取文件

转载 作者:行者123 更新时间:2023-11-30 07:32:12 28 4
gpt4 key购买 nike

这是我使用 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 制作了 SOP 以列出/misc/downloads/路径中的所有文件。

我该怎么做才能解决这个问题?

最佳答案

FileInputStream 尝试从您的本地 文件系统(它不存在)读取文件,而您似乎真的想从远程读取它文件系统。或者你想把它下载到本地系统然后从那里读取?

无论如何,要从远程端下载,请使用来自ChannelSftpget 方法之一。 ,而不是 put(用于上传)。

关于java - 使用 JSch 从另一个位置读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6747993/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com