/** * Create a file and open it for reading and writing. * Same as {@link #createFile(String, SFTPv3FileAttributes) createFile(fileName, null)}. * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileHandle handle * @throws IOException */ public SFTPv3FileHandle createFile(String fileName) throws IOException { return createFile(fileName, null); }
/** * Create a file and open it for reading and writing. * Same as {@link #createFile(String, SFTPv3FileAttributes) createFile(fileName, null)}. * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileHandle handle * @throws IOException the io exception */ public SFTPv3FileHandle createFile(String fileName) throws IOException { return createFile(fileName, null); }
/** * Create a file and open it for reading and writing. * Same as {@link #createFile(String, SFTPv3FileAttributes) createFile(fileName, null)}. * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileHandle handle * @throws IOException */ public SFTPv3FileHandle createFile(String fileName) throws IOException { return createFile(fileName, null); }
/** * Creates a new file and writes to it. * * @param path the path * @return the output stream * @throws IOException the io exception */ public OutputStream writeToFile(String path) throws IOException { final SFTPv3FileHandle h = createFile(path); return new OutputStream() { private long offset = 0; public void write(int b) throws IOException { write(new byte[]{(byte)b}); } public void write(byte[] b, int off, int len) throws IOException { SFTPv3Client.this.write(h,offset,b,off,len); offset += len; } public void close() throws IOException { closeFile(h); } }; }
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("teststackoverflow", "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(); }