Skip to content

Instantly share code, notes, and snippets.

@SteveRuben
Created November 3, 2018 12:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SteveRuben/175678387c8493db90b806b4bf86edd2 to your computer and use it in GitHub Desktop.
Save SteveRuben/175678387c8493db90b806b4bf86edd2 to your computer and use it in GitHub Desktop.
Remote file management on FTP server using Java
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* @author Steve Ruben
* @version 1.0.0
*/
public class FileIOHelper {
/**
*
*/
private static Logger logger = Logger.getLogger(FileIOHelper.class);
private static final String SEPERATOR = "/";
public static final String ENCODE = "UTF-8";
/**
* Check if a given file exists
*
* @author Steve Ruben
* @param path represent file or path to file
* @return boolean true if it's a file and false otherwise
*/
public static boolean fileExists(String path) {
File f = new File(path);
return f.exists() && !f.isDirectory();
}
/**
* delete a file
*
* @param file
*/
public static void deleteFile(String file) {
FileUtils.deleteQuietly(new File(file));
}
/**
* write stream to a given file
*
* @param input incoming stream
* @param directory where we should create a file
* @param filename name of file to create
* @throws IOException
*/
public static void writeToDisk(InputStream input, String directory, String filename) throws IOException {
logger.info("CREATING DIRECTORY : " + directory);
File root = new File(directory);
FileUtils.forceMkdir(root);
boolean result = root.mkdir();
logger.info("DIRECTION CREATION RESULT : " + result);
OutputStream output = new FileOutputStream(new File(directory, filename));
try {
IOUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);
}
}
/**
* write stream to a given file
*
* @param input stream(image) to write on disk
* @param directory place to write input
* @param type type of the file to create
* @param name name of the file to create
* @throws IOException
*/
public static void writeToDisk(BufferedImage input, String directory, String type, String name) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(input, type, os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
writeToDisk(is, directory, name + "." + type);
}
/**
* read specific file from disk
*
* @param filename name of file to read
* @return File file to read
* @throws IOException
*/
public static InputStream readFileFromDisk(String filename) throws IOException {
InputStream input = new FileInputStream(new File(filename));
return input;
}
/**
* transfer file to remote server using ftp
*
* @param servername remote server name
* @param port remote server listener port
* @param username
* @param password
* @param filenames files to transfer
* @exception IOException
*/
public static void tranferFile(String servername, int port, String username, String password,
List<String> filenames) {
FTPClient ftpClient = null;
try {
ftpClient = ftpConnect(servername, port, username, password);
for (String file : filenames) {
File sourceFile = new File(file);
InputStream inputStream = new FileInputStream(sourceFile);
ftpClient.storeFile(sourceFile.getName(), inputStream);
inputStream.close();
}
} catch (IOException e) {
} finally {
try {
ftpDisconnect(ftpClient);
} catch (IOException e) {
System.out.println("Exception occured while ftp logout/disconnect : " + e);
}
}
}
/**
* transfer file to remote server using ftp
*
* @param servername
* @param port
* @param username
* @param password
* @param dirTree
* @param filename
*/
public static void tranferFile(String servername, int port, String username, String password, String dirTree,
String filename) {
FTPClient ftpClient = null;
try {
ftpClient = ftpConnect(servername, port, username, password);
ftpCreateDirectoryTree(ftpClient, dirTree);
File sourceFile = new File(filename);
InputStream inputStream = new FileInputStream(sourceFile);
ftpClient.storeFile(sourceFile.getName(), inputStream);
inputStream.close();
} catch (IOException e) {
} finally {
try {
ftpDisconnect(ftpClient);
} catch (IOException e) {
System.out.println("Exception occured while ftp logout/disconnect : " + e);
}
}
}
/**
* make a directory using hierarchy definition
*
* @param root place to create a directory
* @param dirs list of dir to create
* @param depth number of directory to create
*/
public static void mkDirs(File root, List<String> dirs, int depth) {
if (depth == 0)
return;
for (String s : dirs) {
File subdir = new File(root, s);
subdir.mkdir();
mkDirs(subdir, dirs, depth - 1);
}
}
/**
* Delete a specific file on directory
*
* @param dir
* @return true if it's delete and false otherwise
*/
public static boolean deleteDirectory(File dir) {
if (dir.isDirectory()) {
File[] children = dir.listFiles();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDirectory(children[i]);
if (!success) {
return false;
}
}
}
return dir.delete();
}
/**
* Connect to ftp server
*
* @param servername
* @param port
* @param username
* @param password
* @return
* @throws SocketException
* @throws IOException
*/
private static FTPClient ftpConnect(String servername, int port, String username, String password)
throws SocketException, IOException {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(servername, port);
ftpClient.login(username, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return ftpClient;
}
/**
* Disconnect from ftp server
*
* @param ftpClient
* @throws IOException
*/
private static void ftpDisconnect(FTPClient ftpClient) throws IOException {
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
/**
* Create Directory tree on ftp
*
* @param ftpClient
* @param dirTree
* @throws IOException
*/
private static void ftpCreateDirectoryTree(FTPClient ftpClient, String dirTree) throws IOException {
String[] directories = dirTree.split("/");
boolean dirExists = true;
for (String dir : directories) {
if (!dir.isEmpty()) {
if (dirExists) {
dirExists = ftpClient.changeWorkingDirectory(dir);
}
if (!dirExists) {
if (!ftpClient.makeDirectory(dir)) {
throw new IOException("Unable to create remote directory '" + dir + "'. error='"
+ ftpClient.getReplyString() + "'");
}
if (!ftpClient.changeWorkingDirectory(dir)) {
throw new IOException("Unable to change into newly created remote directory '" + dir
+ "'. error='" + ftpClient.getReplyString() + "'");
}
}
}
}
}
/**
* @param localFolder
* @param remoteFile file to be upload
* @param delete
* @return
* @throws Exception
*/
public static String downloadFile(String servername, int port, String username, String password, String localFolder,
String remoteFile) throws Exception {
FTPClient ftpClient = null;
String file = null;
try {
ftpClient = ftpConnect(servername, port, username, password);
// Activate the passivate mode in order to avoid the connexion being
// block by the firewall
ftpClient.enterLocalPassiveMode();
// Set the file type to make sure any file will be send
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// Transfert du fichier
file = retrieveFile(ftpClient, localFolder, remoteFile);
} catch (IOException e) {
System.out.println("Exception occured while ftp logout/disconnect : " + e);
} finally {
try {
ftpDisconnect(ftpClient);
} catch (IOException e) {
System.out.println("Exception occured while ftp logout/disconnect : " + e);
}
}
return file;
}
/**
* Retrieve specific file on ftp server
*
* @param ftpClient
* @param localFolder
* @param remoteFile
* @return
* @throws Exception
*/
private static String retrieveFile(FTPClient ftpClient, String localFolder, String remoteFile) throws Exception {
File localFile = new File(localFolder);
if (!localFile.exists()) {
localFile.mkdirs();
}
// Build the nom of the file in local;
localFolder = localFolder + SEPERATOR + buildFileName(remoteFile);
File file = new File(localFolder);
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
try {
ftpClient.retrieveFile(remoteFile, outputStream);
} finally {
outputStream.close();
}
return localFolder;
}
/**
*
* @param fileName
* @return
*/
public static String buildFileName(String fileName) {
String[] count = fileName.split(SEPERATOR);
return count[count.length - 1];
}
/**
* Delete remote file
*
* @param servername
* @param port
* @param username
* @param password
* @param fileName
* @throws Exception
*/
public static void deleteRemoteFile(String servername, int port, String username, String password, String fileName)
throws Exception {
FTPClient ftpClient = null;
try {
ftpClient = ftpConnect(servername, port, username, password);
// Activate the passivate mode in order to avoid the connexion being
// block by the firewall
ftpClient.enterLocalPassiveMode();
// Set the file type to make sure any file will be send
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// Transfert du fichier
ftpClient.deleteFile(fileName);
} catch (IOException e) {
} finally {
try {
ftpDisconnect(ftpClient);
} catch (IOException e) {
System.out.println("Exception occured while ftp logout/disconnect : " + e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment