gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:27:53 25 4
gpt4 key购买 nike

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

}

我可能写错了吗?

最佳答案

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

the name of the new file will be generated by concatenating the prefix, five or more internally-generated characters, and the suffix

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

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

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

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

关于java - Ganymed SSH2,创建文件并将文件写入特定目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17045222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com