如何将字符串写入位于远程服务器(Linux)中的文件 [英] How to write a string to a file located in remote server (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 具有 OutputStream .写入OutputStream的所有内容都会写入远程系统上的文件中.您可以将二进制数据写入OutputStream,或者如果要向其中写入文本,则可以将其转换为Writer:
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屋!