Ganymed SSH2,创建文件并将文件写入特定目录

时间:2013-06-11 13:23:36

标签: java file netbeans ssh

我最近开始学习如何使用ssh。 我正在使用Ganymed SSH2在/ bin中创建一个文件并在其中写入文字。 该文件的名称是错误的(Test74024010477125945txt)-thejh帮助我解决了这个问题,并没有写入任何内容! - 不固定 -

代码:

private void sshconnectActionPerformed(java.awt.event.ActionEvent evt) {
    String host = phoneip.getText();
    String username = "root";
    String password = passwd.getText();

    Connection conn = new Connection(host);
    try {
        conn.connect();
    } catch (IOException ex) {
        Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, ex);
        progress.setText("Connection Failed");
    }
    // Done connection stuffs and instance
    try {
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
    } catch (IOException ex) {
        Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, ex);
        progress.setText("Authentication failed");
    }

    try {
        Session sess = conn.openSession();
        sess.execCommand("cd /bin"); //useless i believe 
    } catch (IOException ex) {
        Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, ex);
        progress.setText("Session failed");
    }

    try {
        SFTPv3Client client = new SFTPv3Client(conn);
        File tmpFile = new File("Test.txt");
        FileWriter fw = new FileWriter(tmpFile);
        fw.write("this is a test");
        fw.flush();
        fw.close();
        //temporary file 

        SFTPv3FileHandle handle = client.createFile("/bin/" + tmpFile.getName());
        FileInputStream fis = new FileInputStream(tmpFile); 
        byte[] buffer = new byte[1024];
        int i=0;
        long offset=0;

        while ((i = fis.read(buffer)) != -1) { //start writing to file
            client.write(handle,offset,buffer,0,i);
                           offset+= i;
        }
        //write file at /bin

        client.closeFile(handle);
        if (handle.isClosed())  progress.setText("Done!");;
            client.close();

    } catch (IOException ex) {
        Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, ex);
        progress.setText("SFTP failed"); //failure
    }

}

我有可能写错了吗?

1 个答案:

答案 0 :(得分:1)

在使用内容之前阅读文档总是一个好主意,或者至少在您发现内容无法按照您希望的方式工作时。所以,let's have a look at the documentation of the method you're using:

  

将通过连接前缀,五个或更多内部生成的字符以及后缀来生成新文件的名称

生成的文件的名称以“Test”开头,随后是一串随机字符,以“txt”结尾。怎么了?

如果您需要名为Test.txt的文件,请执行以下操作:

File tmpFile = new File("Test.txt");

然后创建FileWriter实例应该创建文件。