How to write a string to a file located in remote server (linux)

百般思念 提交于 2020-01-24 20:44:09

问题


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.

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.


回答1:


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) {
    ....
}



回答2:


@Kenster answer doesn't work for me (get a 0 bytes file), so I gets another solution:

String content = "some text";
InputStream stream = new ByteArrayInputStream (content.getBytes ());

sftpChannel.put (stream, "/some/remote/file");

Hope it'll help somebody...



来源:https://stackoverflow.com/questions/40590372/how-to-write-a-string-to-a-file-located-in-remote-server-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!