如何将字符串写入位于远程服务器(Linux)中的文件 [英] How to write a string to a file located in remote server (linux)

查看:219
本文介绍了如何将字符串写入位于远程服务器(Linux)中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图构建一个小的代码,我想在其中创建一些字符串并将该字符串传输到位于远程服务器中的文件(应在运行时中创建).在我的情况下,远程服务器是Linux.

I was trying to build an small code where I want to create some string and transfer that string to a file (that should be created in runtime) located in remote server. In my case the remote server is Linux.

有人可以在这里帮助我吗?我正在使用JSCH和ChannelSftp,但无法执行此操作.下面是我的代码:

Can someone help me here? I was using a JSCH and ChannelSftp but unable to do the thing. Below is my code:

JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, MachineIP, SFTPPORT);
String str = "Hello";
session.setPassword(SFTPPASS);
System.out.println(SFTPPASS);
java.util.Properties config = new java.util.Properties();

System.out.println("Config done");
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
System.out.println("Config set");

session.connect();
System.out.println("Session connected");
channel = session.openChannel("sftp");
channel.connect();

System.out.println("Connection Opened\n");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f=new File("Test.txt");
//unable to do anything beyond this.

对不起,如果您发现这个愚蠢的人,但我对此很陌生.

Sorry if you find this stupid but I am very new to it.

推荐答案

ChannelSftp 具有

ChannelSftp has versions of the put method which accept a filename on the remote system and which return an OutputStream. Anything written to the OutputStream is written to the file on the remote system. You can write binary data to an OutputStream, or convert it to a Writer if you want to write text to it:

try (OutputStream out = channelSftp.put("/some/remote/file")) {
    OutputStreamWriter writer = new OutputStreamWriter(out);
    writer.write("some text");
} catch (IOException e) {
    ....
}

这篇关于如何将字符串写入位于远程服务器(Linux)中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆