如何将字符串写入位于远程服务器的文件 (linux)
How to write a string to a file located in remote server (linux)
我试图构建一个小代码,我想在其中创建一些字符串并将该字符串传输到位于远程服务器的文件(应在运行时创建)。在我的例子中,远程服务器是 Linux.
有人可以帮我吗?我正在使用 JSCH 和 ChannelSftp 但无法执行此操作。下面是我的代码:
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.
对不起,如果你觉得这很愚蠢,但我是新手。
ChannelSftp has versions of the put method which accept a filename on the remote system and which return an OutputStream。写入 OutputStream 的任何内容都会写入远程系统上的文件。您可以将二进制数据写入 OutputStream,或者如果要向其写入文本,则将其转换为 Writer:
try (OutputStream out = channelSftp.put("/some/remote/file")) {
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write("some text");
} catch (IOException e) {
....
}
@Kenster 的回答对我不起作用(得到一个 0 字节的文件),所以我得到了另一个解决方案:
String content = "some text";
InputStream stream = new ByteArrayInputStream (content.getBytes ());
sftpChannel.put (stream, "/some/remote/file");
希望它能对某人有所帮助...
我试图构建一个小代码,我想在其中创建一些字符串并将该字符串传输到位于远程服务器的文件(应在运行时创建)。在我的例子中,远程服务器是 Linux.
有人可以帮我吗?我正在使用 JSCH 和 ChannelSftp 但无法执行此操作。下面是我的代码:
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.
对不起,如果你觉得这很愚蠢,但我是新手。
ChannelSftp has versions of the put method which accept a filename on the remote system and which return an OutputStream。写入 OutputStream 的任何内容都会写入远程系统上的文件。您可以将二进制数据写入 OutputStream,或者如果要向其写入文本,则将其转换为 Writer:
try (OutputStream out = channelSftp.put("/some/remote/file")) {
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write("some text");
} catch (IOException e) {
....
}
@Kenster 的回答对我不起作用(得到一个 0 字节的文件),所以我得到了另一个解决方案:
String content = "some text";
InputStream stream = new ByteArrayInputStream (content.getBytes ());
sftpChannel.put (stream, "/some/remote/file");
希望它能对某人有所帮助...