在使用java的ftp下載下傳伺服器上的檔案擷取檔案的byte[],然後對byte進行加密傳輸時,
注意是要擷取byte[],而不是下載下傳檔案到本地;
發現下載下傳的byte[]大小總是小于檔案實際大小,并且下載下傳的大小是變化的
到網上查閱發現,ftp傳輸是不穩定的,會随網絡情況波動;
是以對下載下傳的方法進行了修改;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpProtocolException;
public String download(String ftpFile, FtpClient ftpClient) {
InputStream is = null;
byte[] data = null;
try {
// 擷取ftp上的檔案
long size=ftpClient.getSize(ftpFile);
System.out.println(ftpClient.getSize(ftpFile));
is = ftpClient.getFileStream(ftpFile);
// System.out.println(is.available());
int count =is.available();
System.out.println("count:"+count);
while (count>0 || (data==null?0:data.length)<size) {// 擷取到的大小小于檔案大小也進入
byte[] b = new byte[count];
is.read(b);
System.out.println("b:"+b.length);
data= byteMerger(b,data);
count = is.available();
}
is.close();
ftpClient.close();
}catch (FtpProtocolException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
System.out.println("data size:"+data.length);
String encodeBase64Str =org.apache.commons.codec.binary.Base64.encodeBase64String(data);
return encodeBase64Str;
}
// 參考 https://blog.csdn.net/shb2058/article/details/52637213
public static byte[] byteMerger(byte[] byte1, byte[] byte2){
if (byte1==null && byte2!=null){
return byte2;
}
if (byte2 == null && byte1!=null){
return byte1;
}
if (byte2 == null && byte1 ==null){
return null;
}
byte[] byte3 = new byte[byte1.length+byte2.length];
System.arraycopy(byte1, 0, byte3, 0, byte1.length);
System.arraycopy(byte2, 0, byte3, byte1.length, byte2.length);
return byte3;
}
/***
* 連接配接ftp
* @param url
* @param port
* @param username
* @param password
* @return
*/
public FtpClient connectFTP(String url, int port, String username, String password) {
//建立ftp
FtpClient ftp = null;
try {
//建立位址
SocketAddress addr = new InetSocketAddress(url, port);
//連接配接
ftp = FtpClient.create();
ftp.connect(addr);
//登陸
ftp.login(username, password.toCharArray());
ftp.setBinaryType();
ftp.enablePassiveMode(true);//這句最好加告訴對面伺服器開一個端口
} catch (FtpProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ftp;
}
運作發現果然波動是很大的
參考:
https://blog.csdn.net/shb2058/article/details/52637213