0

我最近开始学习如何使用 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
    }

}

有没有可能我写错了?

4

1 回答 1

1

在使用东西之前阅读文档总是一个好主意,或者至少当你发现东西没有按照你想要的方式工作时。因此,让我们看一下您正在使用的方法的文档:

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

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

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

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

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

于 2013-06-11T13:32:11.903 回答