如何在远程计算机中打开路径并使用java在该路径中写入文件

时间:2014-07-17 08:49:05

标签: java sftp jsch

根据用户输入数据和数据库数据,我需要创建一个文件并将其放在远程机器中。所以我能想到的更好的方法是连接到远程机器并直接在那里写文件。到目前为止使用JSch i连接到远程机器。但我不知道如何在此路径中的特定位置(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/

我之前问过这个问题,但它被标记为重复,我被要求提出一个新问题。这不重复。到目前为止,在之前发布的链接中找不到合适的答案。

1 个答案:

答案 0 :(得分:2)

您可以使用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();  
    }
相关问题