問(wèn)題描述
我正在使用 Apache Commons FTP 上傳文件.在上傳之前,我想檢查該文件是否已存在于服務(wù)器上,并將其備份到同一服務(wù)器上的備份目錄中.
I'm using Apache Commons FTP to upload a file. Before uploading I want to check if the file already exists on the server and make a backup from it to a backup directory on the same server.
有人知道如何將文件從 FTP 服務(wù)器復(fù)制到同一服務(wù)器上的備份目錄嗎?
public static void uploadWithCommonsFTP(File fileToBeUpload){
FTPClient f = new FTPClient();
FTPFile backupDirectory;
try {
f.connect(server.getServer());
f.login(server.getUsername(), server.getPassword());
FTPFile[] directories = f.listDirectories();
FTPFile[] files = f.listFiles();
for(FTPFile file:directories){
if (!file.getName().equalsIgnoreCase("backup")) {
backupDirectory=file;
} else {
f.makeDirectory("backup");
}
}
for(FTPFile file: files){
if(file.getName().equals(fileToBeUpload.getName())){
//copy file to backupDirectory
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
<小時(shí)>
編輯代碼:還是有問(wèn)題,當(dāng)我備份 zip 文件時(shí),備份的文件已損壞.
Edited code: still there is a problem, when i backup zip file, the backup-ed file is corrupted.
有人知道原因嗎?
public static void backupUploadWithCommonsFTP(File fileToBeUpload) {
FTPClient f = new FTPClient();
boolean backupDirectoryExist = false;
boolean fileToBeUploadExist = false;
FTPFile backupDirectory = null;
try {
f.connect(server.getServer());
f.login(server.getUsername(), server.getPassword());
FTPFile[] directories = f.listDirectories();
// Check for existence of backup directory
for (FTPFile file : directories) {
String filename = file.getName();
if (file.isDirectory() && filename.equalsIgnoreCase("backup")) {
backupDirectory = file;
backupDirectoryExist = true;
break;
}
}
if (!backupDirectoryExist) {
f.makeDirectory("backup");
}
// Check if file already exist on the server
f.changeWorkingDirectory("files");
FTPFile[] files = f.listFiles();
f.changeWorkingDirectory("backup");
String filePathToBeBackup="/home/user/backup/";
String prefix;
String suffix;
String fileNameToBeBackup;
FTPFile fileReadyForBackup = null;
f.setFileType(FTP.BINARY_FILE_TYPE);
f.setFileTransferMode(FTP.BINARY_FILE_TYPE);
for (FTPFile file : files) {
if (file.isFile() && file.getName().equals(fileToBeUpload.getName())) {
prefix = FilenameUtils.getBaseName(file.getName());
suffix = ".".concat(FilenameUtils.getExtension(file.getName()));
fileNameToBeBackup = prefix.concat(Calendar.getInstance().getTime().toString().concat(suffix));
filePathToBeBackup = filePathToBeBackup.concat(fileNameToBeBackup);
fileReadyForBackup = file;
fileToBeUploadExist = true;
break;
}
}
// If file already exist on the server create a backup from it otherwise just upload the file.
if(fileToBeUploadExist){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
f.retrieveFile(fileReadyForBackup.getName(), outputStream);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
if(f.storeUniqueFile(filePathToBeBackup, is)){
JOptionPane.showMessageDialog(null, "Backup succeeded.");
f.changeWorkingDirectory("files");
boolean reply = f.storeFile(fileToBeUpload.getName(), new FileInputStream(fileToBeUpload));
if(reply){
JOptionPane.showMessageDialog(null,"Upload succeeded.");
}else{
JOptionPane.showMessageDialog(null,"Upload failed after backup.");
}
}else{
JOptionPane.showMessageDialog(null,"Backup failed.");
}
}else{
f.changeWorkingDirectory("files");
f.setFileType(FTP.BINARY_FILE_TYPE);
f.enterLocalPassiveMode();
InputStream inputStream = new FileInputStream(fileToBeUpload);
ByteArrayInputStream in = new ByteArrayInputStream(FileUtils.readFileToByteArray(fileToBeUpload));
boolean reply = f.storeFile(fileToBeUpload.getName(), in);
System.out.println("Reply code for storing file to server: " + reply);
if(!f.completePendingCommand()) {
f.logout();
f.disconnect();
System.err.println("File transfer failed.");
System.exit(1);
}
if(reply){
JOptionPane.showMessageDialog(null,"File uploaded successfully without making backup." +
"
Reason: There wasn't any previous version of this file.");
}else{
JOptionPane.showMessageDialog(null,"Upload failed.");
}
}
//Logout and disconnect from server
in.close();
f.logout();
f.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
推薦答案
如果你使用的是 apache commons net FTPClient
,有一個(gè)直接的方法可以將文件從一個(gè)位置移動(dòng)到另一個(gè)位置(如果user
有適當(dāng)?shù)臋?quán)限).
If you are using apache commons net FTPClient
, there is a direct method to move a file from one location to another location (if the user
has proper permissions).
ftpClient.rename(from, to);
或者,如果你熟悉 ftp 命令
,你可以使用類(lèi)似
or, If you are familiar with ftp commands
, you can use something like
ftpClient.sendCommand(FTPCommand.yourCommand, args);
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
//command successful;
} else {
//check for reply code, and take appropriate action.
}
如果您使用任何其他客戶(hù)端,請(qǐng)閱讀文檔,客戶(hù)端實(shí)現(xiàn)之間不會(huì)有太大變化.
If you are using any other client, go through the documentation, There wont be much changes between client implementations.
更新:
上述方法將文件移動(dòng)到 to
目錄,即該文件將不再存在于 from
目錄中.基本上 ftp 協(xié)議意味著從 local <-> 傳輸文件.遠(yuǎn)程
或遠(yuǎn)程<->其他遠(yuǎn)程
,但不能在服務(wù)器中傳輸.
Above approach moves the file to to
directory, i.e, the file won't be there in from
directory anymore. Basically ftp protocol meant to be transfer the files from local <-> remote
or remote <-> other remote
but not to transfer with in the server.
這里的工作會(huì)更簡(jiǎn)單,將完整的文件獲取到本地 InputStream
并將其作為備份目錄中的新文件寫(xiě)回服務(wù)器.
The work around here, would be simpler, get the complete file to a local InputStream
and write it back to the server as a new file in the back up directory.
要獲取完整的文件,
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ftpClient.retrieveFile(fileName, outputStream);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
現(xiàn)在,將此流存儲(chǔ)到備份目錄.首先,我們需要將工作目錄更改為備份目錄.
now, store this stream to backup directory. First we need to change working directory to backup directory.
// assuming backup directory is with in current working directory
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//binary files
ftpClient.changeWorkingDirectory("backup");
//this overwrites the existing file
ftpClient.storeFile(fileName, is);
//if you don't want to overwrite it use storeUniqueFile
希望對(duì)你有所幫助..
這篇關(guān)于java - 如何將FTP服務(wù)器上的文件復(fù)制到Java中同一服務(wù)器上的目錄?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!