Transfer string content to a file in remote machine using java

↘锁芯ラ 提交于 2019-12-22 12:26:08

问题


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

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