连接服务器读取文件java

连接服务器,读取指定文件,并返回。
这里引用了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();

返回文件读取的内容。

如果思路有误或者大家有更好的方法,欢迎交流和指正。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值