问题
I need to place a string content in a remote file.
Ideally, I used to create a file in local and then transfer that file to remote machine.
Below is the code snippet I used, to copy file to remote.
ChannelSftp sftpChannel = (ChannelSftp) channel;
File file = new File(filePathWithName);//To read the file in local machine
try {
sftpChannel.cd(location);//Remote location
//Transferring the file to RemoteLocation.
sftpChannel.put(new FileInputStream(file), file.getName());//.(Here I don't want read a file.) //Instead I want copy a content which is in string variable, something like below two lines, to the remote location.
String content = "abcdefg";
sftpChannel.put(content,"someFileName")
} catch (SftpException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
sftpChannel.exit();
Is there any reference or documentation to overcome reading a file in local to create the same in remote machine.
-Thank You
回答1:
If I understand your problem correctly, you'd like to be able to copy some string data to a remote machine without reading a file locally. If you look at the javadoc, put
accepts InputStream
. So you do:
InputStream stream = new ByteArrayInputStream(content.getBytes());
sftpChannel.put(stream, "name.txt");
Note that you can also put(String dst)
where you can write to the OutputStream
that is returned. But I didn't show that.
来源:https://stackoverflow.com/questions/38837916/transfer-string-content-to-a-file-in-remote-machine-using-java