Java – Get List of Files from FTP Server

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.io.FileUtils;
import java.io.IOException;

public class Main {

	public static void main(String[] args) {
		FTPClient client = new FTPClient();

		client.connect("ftp.domain.com");
		client.login("admin", "secret");

		String[] names = client.listNames();
		for (String name : names) {
			System.out.println("Name = " + name);
		}

		FTPFile[] ftpFiles = client.listFiles();
		for (FTPFile ftpFile : ftpFiles) {
			// Check if FTPFile is a regular file
			if (ftpFile.getType() == FTPFile.FILE_TYPE) {
				System.out.println("FTPFile: " + ftpFile.getName() + "; "
						+ FileUtils.byteCountToDisplaySize(ftpFile.getSize()));
			}
		}
		client.logout();
		client.disconnect();
	}

}

Java – Change File Date / Time using Commons FileUtils

import java.io.IOException;
import org.apache.commons.io.FileUtils;

import java.io.File;

public class Main {

	public static void main(String[] args) {
		try {
			File file = new File("pic.jpg");
			long lastModified1 = file.lastModified();
			FileUtils.touch(file);
			long lastModified2 = file.lastModified();
			System.out.println("File date / time was updated: " + (lastModified2 > lastModified1));
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}

Output:

File date / time was updated: true

Java – Create File Object from URL using Commons FileUtils

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;

public class URLToFile {

	public static void main(String[] args) throws Exception {
		//
		// FileUtils.toFile(URL url) convert from URL the File.
		//
		String data = FileUtils.readFileToString(FileUtils.toFile(
				URLToFile.class.getResource("/data.txt")));
		System.out.println("data = " + data);

		//
		// Creates a URL with file protocol and convert it into File
		// object.
		//
		File file = FileUtils.toFile(new URL("file://D:/demo.txt"));
		data = FileUtils.readFileToString(file);
		System.out.println("data = " + data);
	}

}

Page 1 of 212