简体   繁体   中英

How to write a string to a file located in remote server (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.

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.

@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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM