![](/img/trans.png)
[英]Write a file to a remote location using Java with network path or drive?
[英]How to open a path in remote machine and write a file in that path using java
基於用戶輸入數據和數據庫數據,我需要創建一個文件並將其放置在遠程計算機中。 因此,我能想到的更好的方法是連接到遠程計算機並直接將文件寫入那里。 到目前為止,我已使用JSch
連接到遠程計算機。 但是我不知道如何在此路徑的特定位置(root/usr/path/)
中寫入文件,我需要寫入並放置文件(ddr12213124.NEW or ddr12213124.CSV)
。
我已經附加了用於連接到遠程計算機的代碼
package com.trial.classes;
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.UserInfo;
public class transferFile {
public static void main(String[] args) {
// TODO Auto-generated method stub
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("ragesh", "10.0.0.1", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");
session.connect();
System.out.println("Connected to session successfully");
Channel channel = session.openChannel("sftp");
channel.connect();
System.out.println("Connected to Channel successfully");
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
}
}
}
現在我想創建一個文件(ddr12213124.NEW or ddr12213124.CSV)
並將其放置在路徑root/usr/path/
我早些時候問過這個問題,但它被標記為重復,並被要求提出一個新問題。 這不是重復的。 到目前為止,在先前發布的鏈接中找不到合適的答案。
您可以使用ChannelSFTP#put方法將文件寫入遠程目錄。 put方法有多種風格,您可以根據需要使用任意一種。 以下是將文件從本地系統寫入遠程系統的示例代碼:
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("ragesh", "10.0.0.1", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");
session.connect();
System.out.println("Connected to session successfully");
Channel channel = session.openChannel("sftp");
channel.connect();
System.out.println("Connected to Channel successfully");
ChannelSftp sftpChannel = (ChannelSftp) channel;
// this will read file with the name test.txt and write to remote directory
sftpChannel.cd("/root/usr/path");
File f = new File("test.txt");
sftpChannel.put(new FileInputStream(f), f.getName()); // here you can also change the target file name by replacing f.getName() with your choice of name
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.