连接服务器,读取指定文件,并返回。
这里引用了jsch-0.1.53-sources.jar和jsch-0.1.53.jar
具体的代码如下:
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class Demo {
static String userName;
static String host;
static int port;
static String password;
public static StringBuffer readFile(String path) {
Session session = null;
JSch jsch = new JSch();
try {
if (port <= 0) {
// 连接服务器,采用默认端口
session = jsch.getSession(userName, host);
} else {
// 采用指定的端口连接服务器
session = jsch.getSession(userName, host, port);
}
// 如果服务器连接不上,则抛出异常
if (session == null) {
throw new Exception("session is null");
}
// 设置登陆主机的密码
session.setPassword(password);// 设置密码
// 设置第一次登陆的时候提示,可选值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
// 设置登陆超时时间SFTPUtils.FTP_BASE_PATH.concat(sourcePath)
session.connect(300000);
return readLoadFile(session, path);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static StringBuffer readLoadFile(Session session, String path)
throws SftpException {
Channel channel = null;
StringBuffer sb = null;
try {
channel = (Channel) session.openChannel("sftp");
channel.connect(10000000);
ChannelSftp sftp = (ChannelSftp) channel;
BufferedReader in = null;
try {
HttpURLConnection conn = null;
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(20 * 1000);
InputStream inputStream = conn.getInputStream();
in = new BufferedReader(new InputStreamReader(inputStream));
while (in.ready()) {
//sb = (new StringBuffer(in.readLine()));
sb= sb.append(in.readLine());
System.out.println(sb);
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sftp.quit();
channel.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} finally {
session.disconnect();
channel.disconnect();
}
return sb;
}
}
调用:
String content = Demo.readFile("服务器文件地址").toString();
返回文件读取的内容。
如果思路有误或者大家有更好的方法,欢迎交流和指正。