Download a Sample Netbeans Project Here
INDEX:
- Copy A Directory
- FTP – Upload / Download
- SFTP – Upload / Download
- Connect to a MySQL Database
- Export Data to Excel
- Remove a Directory
- Directory – Zipping
- Directory – Unzipping
Directory – Unzipping
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
*
* @author 3GUSER
*/
public class UnzipADirectory implements Runnable {
private File cZip = null,
cExtractTo = null;
public UnzipADirectory(File cZip, File cExtractTo) {
this.cZip = cZip;
this.cExtractTo = cExtractTo;
}
private void unzipDirectory(File zip, File extractTo) throws IOException {
ZipFile archive = new ZipFile(zip);
Enumeration e = archive.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
File file = new File(extractTo, entry.getName());
if (entry.isDirectory() && !file.exists()) {
file.mkdirs();
} else {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
InputStream in = archive.getInputStream(entry);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[1024];
int read;
while (-1 != (read = in.read(buffer))) {
out.write(buffer, 0, read);
}
in.close();
out.close();
}
}
}
public void run() {
try {
unzipDirectory(cZip, cExtractTo);
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}
Directory – Zipping
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*
* @author Kobus
*/
public class ZipADirectory implements Runnable {
private File cDirectoryToZip = null,
cZipFile = null;
/**
*
* @param cDirectoryToZip - The source directory
* @param cZipFile - The target zip file.
*/
public ZipADirectory(File cDirectoryToZip, File cZipFile) {
this.cDirectoryToZip = cDirectoryToZip;
this.cZipFile = cZipFile;
}
private void zipDirectory(File directoryToZip, File zipFile) throws IOException {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
zip(directoryToZip, directoryToZip, zos);
zos.close();
}
private void zip(File directory, File base, ZipOutputStream zos) throws IOException {
File[] files = directory.listFiles();
byte[] buffer = new byte[1024];
int read = 0;
for (int i = 0, n = files.length; i < n; i++) {
if (files[i].isDirectory()) {
zip(files[i], base, zos);
} else {
System.out.println("Zipping: " + files[i].getName());
FileInputStream in = new FileInputStream(files[i]);
ZipEntry entry = new ZipEntry(files[i].getPath().substring(base.getPath().length() + 1));
zos.putNextEntry(entry);
while (-1 != (read = in.read(buffer))) {
zos.write(buffer, 0, read);
}
in.close();
}
}
}
public void run() {
try {
zipDirectory(cDirectoryToZip, cZipFile);
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}
Remove a Directory
import java.io.File;
/**
*
* @author Kobus
*/
public class RemoveADirectory implements Runnable {
private File cDirectory = null;
/**
*
* @param cDirectory - Directory to delete.
*/
public RemoveADirectory(File cDirectory) {
this.cDirectory = cDirectory;
}
private boolean deleteDirectory(File directory) {
if (directory.isDirectory()) {
String[] children = directory.list();
for (int i = 0; i < children.length; i++) {
System.out.println("Deleting: " + children[i]);
boolean success = deleteDirectory(new File(directory, children[i]));
if (!success) {
System.out.println("Failed to delete the following file: " + children[i]);
return false;
}
}
}
return directory.delete();
}
public void run() {
deleteDirectory(cDirectory);
}
}
Export Data to Excel
Download the libraries: Excel Libraries
Back to index
import java.io.File;
import java.io.IOException;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
/**
*
* @author Kobus
*/
public class ExportToExcel {
WritableWorkbook workbook = null;
WritableSheet sheet = null;
public ExportToExcel(File exportFile, String sheetName) throws IOException {
workbook = Workbook.createWorkbook(exportFile);
sheet = workbook.createSheet(sheetName, 0);
}
public void newSheet(String sheetName) {
sheet = workbook.createSheet(sheetName, 0);
}
public void addLabel(int col, int row, String data) {
try {
Label label = new Label(col, row, data);
sheet.addCell(label);
} catch (WriteException ex) {
System.err.println(ex.getMessage());
}
}
public void addNumber(int col, int row, int data) {
try {
Number number = new Number(col, row, data);
sheet.addCell(number);
} catch (WriteException ex) {
System.err.println(ex.getMessage());
}
}
public void closeExport() {
try {
workbook.write();
workbook.close();
} catch (IOException ex) {
System.err.println(ex.getMessage());
} catch (WriteException ex) {
System.err.println(ex.getMessage());
}
}
}
Connect to a MySQL Database
Download the libraries: MySQL Libraries
Back to index
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author Kobus
*/
public class ConnectToMySQL {
private Connection conn = null;
String databaseServer = null,
databaseName = null,
username = null,
password = null;
public ConnectToMySQL(String databaseServer, String databaseName, String username, String password) {
this.databaseServer = databaseServer;
this.databaseName = databaseName;
this.username = username;
this.password = password;
}
public Connection connectToDatabase() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://" + databaseServer + "/" + databaseName, username, password);
if(!conn.isClosed()) {
System.out.println("Connected to database.");
return conn;
} else {
System.out.println("No database connection was found.");
return null;
}
} catch(ClassNotFoundException ex) {
System.out.println("ClassNotFoundException\n- - - - -\n" + ex.getMessage());
return null;
} catch(SQLException ex) {
System.out.println("SQLException\n- - - - -\n" + ex.getMessage());
return null;
}
}
public void disconnectFromDatabase() {
try {
conn.close();
} catch(SQLException ex) {
System.err.println(ex.getMessage());
}
}
}
SFTP - Upload / Download
Download the libraries: J2SSH Libraries
Back to index
import com.sshtools.j2ssh.FileTransferProgress;
import com.sshtools.j2ssh.SftpClient;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import java.io.IOException;
/**
*
* @author 3GUSER
*/
public class SFTP {
private String remoteServer = "",
username = "",
password = "";
public SFTP(String remoteServer, String username, String password) {
this.remoteServer = remoteServer;
this.username = username;
this.password = password;
}
public void upload(String localFilePath, String remoteFilePath) throws IOException {
SshClient ssh = new SshClient();
ssh.connect(remoteServer, 22);
PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
passwordAuthenticationClient.setUsername(username);
passwordAuthenticationClient.setPassword(password);
int result = ssh.authenticate(passwordAuthenticationClient);
if (result != AuthenticationProtocolState.COMPLETE) {
System.out.println("Login to " + remoteServer + ":" + 22 + " " + username + "/" + password + " failed");
}
SftpClient client = ssh.openSftpClient();
if (!client.isClosed()) {
client.mkdirs(remoteFilePath.substring(0, remoteFilePath.lastIndexOf("/")));
FileTransferProgress progress = new FileTransferProgress() {
public void started(long len, String file) {
System.out.println("Uploading Started.\nFile: " + file + "\nSize: " + len);
}
public boolean isCancelled() {
return false;
}
public void progressed(long len) {
System.out.println("Current Progress: " + len + " bytes.");
}
public void completed() {
System.out.println("Uploading Complete.");
}
};
client.put(localFilePath, remoteFilePath, progress);
}
client.quit();
ssh.disconnect();
}
public void download(String remoteFilePath, String localFilePath) throws IOException {
SshClient ssh = new SshClient();
ssh.connect(remoteServer, 22);
PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
passwordAuthenticationClient.setUsername(username);
passwordAuthenticationClient.setPassword(password);
int result = ssh.authenticate(passwordAuthenticationClient);
if (result != AuthenticationProtocolState.COMPLETE) {
System.out.println("Login to " + remoteServer + ":" + 22 + " " + username + "/" + password + " failed");
}
SftpClient client = ssh.openSftpClient();
if (!client.isClosed()) {
FileTransferProgress prog = new FileTransferProgress() {
public void started(long len, String file) {
System.out.println("Downloading Started.\nFile: " + file + "\nSize: " + len);
}
public boolean isCancelled() {
return false;
}
public void progressed(long len) {
System.out.println("Current Progress: " + len + " bytes.");
}
public void completed() {
System.out.println("Downloading Complete.");
}
};
client.get(remoteFilePath, localFilePath, prog);
}
client.quit();
ssh.disconnect();
}
}
FTP - Upload / Download
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
*
* @author 3GUSER
*/
public class FTP {
private String remoteServer = "",
username = "",
password = "";
public FTP(String remoteServer, String username, String password) {
this.remoteServer = remoteServer;
this.username = username;
this.password = password;
}
public void upload(File localFile, String remoteFilePath) throws MalformedURLException, IOException {
if (remoteServer != null && remoteFilePath != null && localFile != null) {
StringBuffer sb = new StringBuffer("ftp://");
// check for authentication else assume its anonymous access.
if (username != null && password != null) {
sb.append(username);
sb.append(':');
sb.append(password);
sb.append('@');
}
sb.append(remoteServer);
sb.append('/');
sb.append(remoteFilePath);
/*
* type ==> a=ASCII mode, i=image (binary) mode, d= file directory
* listing
*/
sb.append(";type=i");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
URL url = new URL(sb.toString());
URLConnection urlc = url.openConnection();
bos = new BufferedOutputStream(urlc.getOutputStream());
bis = new BufferedInputStream(new FileInputStream(localFile));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) != -1) {
bos.write(i);
}
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
} else {
System.out.println("Input not available.");
}
}
public void download(String remoteFilePath, File localFile) throws MalformedURLException, IOException {
if (remoteServer != null && remoteFilePath != null && localFile != null) {
StringBuffer sb = new StringBuffer("ftp://");
// check for authentication else assume its anonymous access.
if (username != null && password != null) {
sb.append(username);
sb.append(':');
sb.append(password);
sb.append('@');
}
sb.append(remoteServer);
sb.append('/');
sb.append(remoteFilePath);
/*
* type ==> a=ASCII mode, i=image (binary) mode, d= file directory
* listing
*/
sb.append(";type=i");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
URL url = new URL(sb.toString());
URLConnection urlc = url.openConnection();
bis = new BufferedInputStream(urlc.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(localFile.getName()));
int i;
while ((i = bis.read()) != -1) {
bos.write(i);
}
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
} else {
System.out.println("Input not available");
}
}
}
Copy A Directory
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
*
* @author Kobus
*/
public class CopyADirectory implements Runnable {
private File csourcePath = null,
ctargetPath = null;
/**
*
* @param csourcePath - The source location to copy from.
* @param ctargetPath - The target location to copy to.
*/
public CopyADirectory(File csourcePath, File ctargetPath) {
this.csourcePath = csourcePath;
this.ctargetPath = ctargetPath;
}
private void copyDirectory(File sourcePath, File targetPath) throws IOException {
if (sourcePath.isDirectory()) {
if (!targetPath.exists()) {
targetPath.mkdirs();
}
File children[] = sourcePath.listFiles();
for (int a = 0; a < children.length; a++) {
try {
copyDirectory(new File(sourcePath, children[a].getName()), new File(targetPath, children[a].getName()));
} catch (IOException ex) {
System.err.println(ex.getMessage());
continue;
}
}
} else {
System.out.println("Copying: " + sourcePath.getName());
InputStream is = new FileInputStream(sourcePath);
OutputStream os = new FileOutputStream(targetPath);
byte buffer[] = new byte[1024];
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
is.close();
os.close();
}
}
public void run() {
try {
copyDirectory(csourcePath, ctargetPath);
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}