simpleFTP

public class SimpleFTP {


private static String TAG = "SimpleFTP";


private static boolean DEBUG = true;


private Socket socket = null;


private BufferedReader reader = null;


private BufferedWriter writer = null;

private Socket mDataSocket = null;


/**
* Create an instance of SimpleFTP.
*/
public SimpleFTP() {


}


/**
* Connects to the default port of an FTP server and logs in as
* anonymous/anonymous.
*/
public synchronized void connect(String host) throws IOException {
connect(host, 21);
}


/**
* Connects to an FTP server and logs in as anonymous/anonymous.
*/
public synchronized void connect(String host, int port) throws IOException {
connect(host, port, "anonymous", "anonymous");
}


/**
* Connects to an FTP server and logs in with the supplied username and
* password.
*/
public synchronized void connect(String host, int port, String user,
String pass) throws IOException {
if (socket != null) {
throw new IOException(
"SimpleFTP is already connected. Disconnect first.");
}

socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(host, port);
socket.connect(socketAddress, 5000);
reader = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream()));


String response = readLine();
if (response == null || !response.startsWith("220 ")) {
throw new IOException(
"SimpleFTP received an unknown response when connecting to the FTP server: "
+ response);
}


sendLine("USER " + user);


response = readLine();
if (response == null || !response.startsWith("331 ")) {
/*throw new IOException(
"SimpleFTP received an unknown response after sending the user: "
+ response);*/
}


sendLine("PASS " + pass);


response = readLine();
if (response == null || !response.startsWith("230 ")) {
/*throw new IOException(
"SimpleFTP was unable to log in with the supplied password: "
+ response);*/
}


// Now logged in.
}


/**
* Disconnects from the FTP server.
*/
public synchronized void disconnect() throws IOException {
try {
sendLine("QUIT");
} finally {
socket = null;
}
}


/**
* Returns the working directory of the FTP server it is connected to.
*/
public synchronized String pwd() throws IOException {
sendLine("PWD");
String dir = null;
String response = readLine();
if (response != null && response.startsWith("257 ")) {
int firstQuote = response.indexOf('\"');
int secondQuote = response.indexOf('\"', firstQuote + 1);
if (secondQuote > 0) {
dir = response.substring(firstQuote + 1, secondQuote);
}
}
return dir;
}


/**
* Changes the working directory (like cd). Returns true if successful.
*/
public synchronized boolean cwd(String dir) throws IOException {
sendLine("CWD " + dir);
String response = readLine();
return (response.startsWith("250 "));
}


/**
* Sends a file to be stored on the FTP server. Returns true if the file
* transfer was successful. The file is sent in passive mode to avoid NAT or
* firewall problems at the client end.
*/
public synchronized boolean stor(File file) throws IOException {
if (file.isDirectory()) {
throw new IOException("SimpleFTP cannot upload a directory.");
}


String filename = file.getName();


return stor(new FileInputStream(file), filename);
}


/**
* Sends a file to be stored on the FTP server. Returns true if the file
* transfer was successful. The file is sent in passive mode to avoid NAT or
* firewall problems at the client end.
*/
public synchronized boolean stor(InputStream inputStream, String filename)
throws IOException {
BufferedInputStream input = new BufferedInputStream(inputStream);
Socket dataSocket = getConnection();
sendLine("STOR " + filename);


String response = readLine();
if (response == null || !response.startsWith("150 ")) {
throw new IOException(
"SimpleFTP was not allowed to send the file: " + response);
}


BufferedOutputStream output = new BufferedOutputStream(dataSocket
.getOutputStream());
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
output.flush();
output.close();
input.close();


response = readLine();
return response.startsWith("226 ");
}


/**
* Enter binary mode for sending binary files.
*/
public synchronized boolean bin() throws IOException {
sendLine("TYPE I");
String response = readLine();
return (response.startsWith("200 "));
}


/**
* Enter ASCII mode for sending text files. This is usually the default
* mode. Make sure you use binary mode if you are sending images or other
* binary data, as ASCII mode is likely to corrupt them.
*/
public synchronized boolean ascii() throws IOException {
sendLine("TYPE A");
String response = readLine();
return (response.startsWith("200 "));
}


/**
* Sends a raw command to the FTP server.
*/
private void sendLine(String line) throws IOException {
if (socket == null || writer == null) {
throw new IOException("SimpleFTP is not connected.");
}
try {
writer.write(line + "\r\n");
writer.flush();
if (DEBUG) {
Log.d(TAG, "> " + line);
}
} catch (IOException e) {
socket = null;
throw e;
}
}


private String readLine() throws IOException {
String line = reader.readLine();
if (DEBUG) {
Log.d(TAG, "< " + line);
}
return line;
}


/**
* Return the size of a file.
*/
public long getFileSize(String fileName) throws IOException {


sendLine("SIZE " + fileName);
long size = 0;
String response = readLine();
if (response.startsWith("213")) {
size = Integer.parseInt(response.substring(4));
} else {
throw new IOException(response.substring(4));
}


return size;


}


/**
* If the value of mode is true, set binary mode for downloads. Else, set
* Ascii mode.
*/
public void setBinaryMode(Boolean mode) throws IOException {


if (mode) {
sendLine("TYPE I");
} else {
sendLine("TYPE A");
}
String response = readLine();
Log.d("FTP", "setBinaryMode response--" + response);
if (response == null || !response.startsWith("200")) {
// throw new IOException("SimpleFTP can not set BinaryMode.");
}
}


//下載文件
public synchronized void download(String remFileName, String savePath)
throws IOException {
mDataSocket = getConnection();
sendLine("RETR " + remFileName);
String response = readLine();
if (response != null && !response.startsWith("150 ")) {
throw new IOException("SimpleFTP was not allowed to get the file: "
+ response);
}
File file = new File(savePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (Exception e) {
}


// 構造傳輸文件用的數據流
BufferedInputStream bis = new BufferedInputStream(mDataSocket
.getInputStream());
// 接收來自服務器的數據,寫入本地文件
int n;
byte[] buff = new byte[1024];
while ((n = bis.read(buff)) > 0) {
fos.write(buff, 0, n);
}
fos.flush();
fos.close();

response = readLine();
closeDataSocket();


}

public void stopDownload() throws IOException {
closeDataSocket();
}


private void closeDataSocket() throws IOException {
if (mDataSocket != null) {
mDataSocket.close();
mDataSocket = null;
}
}


public String getFileInfo(String fileName) throws IOException {


String result = null;
mDataSocket = getConnection();
sendLine("LIST");

// 構造傳輸文件用的數據流
BufferedInputStream bis = new BufferedInputStream(mDataSocket
.getInputStream());
// 接收來自服務器的數據,寫入本地文件
int n;
byte[] buff = new byte[65530];
while ((n = bis.read(buff)) > 0) {
String str = new String(buff,0,n);
if(str.contains(fileName)){
Log.d(TAG, str);
result = str;

String[] infos = str.split("\n");
if (infos.length > 1) {
for (String info : infos) {
if (info.contains(fileName)) {
result = info;
}
}
}
}
}

closeDataSocket();
readLine();
readLine();
return result;


}

public synchronized Vector<String> List() throws IOException {
Socket dataSocket = getConnection();
sendLine("LIST");
Vector<String> result = new Vector<String>();
int n;
byte[] buff = new byte[65530];
// 準備讀取數據用的流
BufferedInputStream dataInput = new BufferedInputStream(dataSocket
.getInputStream());
// 讀取目錄信息


while ((n = dataInput.read(buff)) > 0) {
System.out.write(buff, 0, n);
result.add(new String(buff, 0, n));
}
dataSocket.close();
readLine();
readLine();


return result;
}


private Socket getConnection() throws IOException {
sendLine("PASV");
String response = readLine();
Log.d("FTP", "getConnection response:" + response);
if (response == null || !response.startsWith("227 ")) {
throw new
IOException("SimpleFTP could not request passive mode: "
+ response);
}


String ip = null;
int port = -1;
int opening = response.indexOf('(');
int closing = response.indexOf(')', opening + 1);
if (closing > 0) {
String dataLink = response.substring(opening + 1, closing);
StringTokenizer tokenizer = new StringTokenizer(dataLink, ",");
try {
ip = tokenizer.nextToken() + "." + tokenizer.nextToken() + "."
+ tokenizer.nextToken() + "." + tokenizer.nextToken();
port = Integer.parseInt(tokenizer.nextToken()) * 256
+ Integer.parseInt(tokenizer.nextToken());
} catch (Exception e) {
throw new IOException(
"SimpleFTP received bad data link information: "
+ response);
}
}
Log.d("FTP", "ip +port  ::" + ip + "+" + port);
Socket dataSocket = new Socket(ip, port);
return dataSocket;
}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章