Ganymed API: использование SFTP
Я использую Ganymed API для подключения к серверу Unix. Я могу создать файл на сервере, но содержимое файла всегда пусто.
Расположение API Ganymed: http://www.ganymed.ethz.ch/ssh2/
Код:
function (ByteArrayOutputStream reportBytes){
// reportBytes is a valid ByteArrayOutputStream
// if I write it to a file in to a local directory using reportBytes.writeTo(fout);
// I can see the contents */
byte byteArray[]=reportBytes.toByteArray();
SFTPv3FileHandle SFTPFILEHandle=sftpClient.createFileTruncate("test.txt");
//The file is created successfully and it is listed in unix
// The permissions of the file -rw-r--r-- 1 test.txt
sftpClient.write(SFTPFILEHandle, 0, byteArray, 0,byteArray.length );
//The above line doesnt seem to work, the file is always empty
}
/* write function definition is */
public void write(SFTPv3FileHandle handle, long fileOffset, byte[] src, int srcoff, int len) throws IOException
Может кто-нибудь сказать мне, если я делаю что-то здесь не так
2 ответа
Я попытался решить вашу проблему, и я оказался в той же ситуации, созданный файл остается пустым.
Тем не менее, я думаю, что нашел причину проблемы.
Вот выдержка из метода ch.ethz.ssh2.SFTPv3Client.write() API-интерфейса ganymed
/**
* Write bytes to a file. If <code>len</code> > 32768, then the write operation will
* be split into multiple writes.
*
* @param handle a SFTPv3FileHandle handle.
* @param fileOffset offset (in bytes) in the file.
* @param src the source byte array.
* @param srcoff offset in the source byte array.
* @param len how many bytes to write.
* @throws IOException
*/
public void write(SFTPv3FileHandle handle, long fileOffset, byte[] src, int srcoff, int len) throws IOException
{
checkHandleValidAndOpen(handle);
if (len < 0)
while (len > 0)
{
Видите ли, когда вы отправляете данные для записи, len> 0, и из-за фиктивного условия метод сразу возвращается и никогда не входит в цикл while (который фактически что-то записывает в файл).
Я предполагаю, что после выражения if (len < 0) было какое-то утверждение, но кто-то забрал его и оставил нам бесполезный кусок кода...
Обновить:
Перейти получить последнюю версию (в примере выше использовалась сборка 210). У меня не было проблем со сборкой 250 и 251.
Вот мой код, и он правильно пишет в новый файл на моем SSH-сервере.
вам нужно будет пуленепробиваемый это:)
public static void main(String[] args) throws Exception {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
SFTPv3Client client = new SFTPv3Client(conn);
File tmpFile = File.createTempFile("teststackru", "dat");
FileWriter fw = new FileWriter(tmpFile);
fw.write("this is a test");
fw.flush();
fw.close();
SFTPv3FileHandle handle = client.createFile(tmpFile.getName());
FileInputStream fis = new FileInputStream(tmpFile);
byte[] buffer = new byte[1024];
int i=0;
long offset=0;
while ((i = fis.read(buffer)) != -1) {
client.write(handle,offset,buffer,0,i);
offset+= i;
}
client.closeFile(handle);
if (handle.isClosed()) System.out.println("closed");;
client.close();
}
Ответ Тони выше с полным классом и импортом. Вам нужно будет добавить банки ganymed и jsch:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SFTPv3Client;
import ch.ethz.ssh2.SFTPv3FileHandle;
public class GanyMedFTP {
public static void main(String[] args) {
Connection conn = new Connection("serverip");
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword("myusername", "mypassword");
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
SFTPv3Client client = new SFTPv3Client(conn);
String fileName="OddyRoxxx.txt";
File tmpFile = File.createTempFile(fileName, "dat");
SFTPv3FileHandle handle = client.createFile(fileName);
FileInputStream fis = new FileInputStream(tmpFile);
byte[] buffer = new byte[1024];
int i=0;
long offset=0;
while ((i = fis.read(buffer)) != -1) {
client.write(handle,offset,buffer,0,i);
offset+= i;
}
client.closeFile(handle);
if (handle.isClosed()) System.out.println("closed");;
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}