15 10 2008

Easily ftp access with Java

I'd like to share at following code that my java class which contains ftp download and upload methods. Hope to enjoy it!

Note: Here the buffer has been set to 32MB (33554432), It is recommended to set it dynmically depend on the file size in your code.

package muco;

import java.io.*;
import java.net.*;

public class FTPClient {
public final String host;
public final String user;
protected final String password;
protected URLConnection urlc;
public FTPClient(String _host, String _user, String _password) {
host= _host; user= _user; password= _password;
urlc = null;
}
private URL makeURL(String targetfile) throws MalformedURLException {
if (user== null)
return new URL("ftp://"+ host+ "/"+ targetfile+ ";type=i");
else
return new URL("ftp://"+ user+ ":"+ password+ "@"+ host+ "/"+ targetfile+ ";type=i");
}
protected InputStream openDownloadStream(String targetfile) throws Exception {
URL url= makeURL(targetfile);
urlc = url.openConnection();
InputStream is = urlc.getInputStream();
return is;
}
protected OutputStream openUploadStream(String targetfile) throws Exception {
URL url= makeURL(targetfile);
urlc = url.openConnection();
OutputStream os = urlc.getOutputStream();
return os;
}
protected void close() {
urlc= null;
}
public void Upload(String _localfile, String _targetfile) {
try {
OutputStream os= openUploadStream(_targetfile);
FileInputStream is= new FileInputStream(_localfile);
byte[] buf= new byte[33554432];
int c;
while (true) {
//System.out.print(".");
c= is.read(buf);
if (c<= 0) break;
//System.out.print("[");
os.write(buf, 0, c);
//System.out.print("]");
}
os.close();
is.close();
close();
}catch(Exception E) {
System.err.println(E.getMessage());
E.printStackTrace();
}
}
public void Download(
String _localfile, String _targetfile) {
try {
InputStream is= openDownloadStream(_targetfile);
FileOutputStream os= new FileOutputStream(_localfile);
byte[] buf= new byte[33554432];
int c;
while (true) {
c= is.read(buf);
if (c<= 0) break;
os.write(buf, 0, c);
}
is.close();
os.close();
close();
}catch(Exception E) {
System.err.println(E.getMessage());
E.printStackTrace();
}
}
}

0 yorum: