Java Tutorial – Using JCIFS to copy files to shared network drive using username and password

This is a quick and dirty example of how you can copy the files to shared network drive. We have tested this under Microsoft Windows, Mac and Linux platforms. To do the actual file copy, we have used an readily available and highly popular API called JCIFS. JCIFS is an Open Source client library that implements the CIFS/SMB networking protocol in 100% Java. CIFS is the standard file sharing protocol on the Microsoft Windows platform. Visit their website at: jcifs.samba.org if you want to download this API.

As you can see in the sample program below, it allows you to even connect to protected network shares using userid and password.

package com.kushal.tools;

/**
 * @author Kushal Paudyal
 * Create on 2012-10-12
 * Last Modified On 2012-10-12
 * www.sanjaal.com/java, www.icodejava.com
 *
 * JCIFS is an Open Source client library that implements the CIFS/SMB networking protocol in 100% Java.
 * CIFS is the standard file sharing protocol on the Microsoft Windows platform
 * Visit their website at: jcifs.samba.org
 *
 * Uses: jcifs-1.1.11.jar
 *
 */
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;

public class NetworkShareFileCopy {
	static final String USER_NAME = "admin";
    static final String PASSWORD = "password";
    //e.g. Assuming your network folder is: \my.myserver.netsharedpublicphotos
    static final String NETWORK_FOLDER = "smb://my.myserver.net/shared/public/photos";

	public static void main(String args[]) {
		String fileContent = "This is a test file";

		new NetworkShareFileCopy().copyFiles(fileContent, "testFile.text");
	}

	public boolean copyFiles(String fileContent, String fileName) {
		boolean successful = false;
		 try{
	            String user = USER_NAME + ":" + PASSWORD;
	            System.out.println("User: " + user);

	            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
	            String path = NETWORK_FOLDER + fileName;
	            System.out.println("Path: " +path);

	            SmbFile sFile = new SmbFile(path, auth);
	            SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
	            sfos.write(fileContent.getBytes());

	            successful = true;
	            System.out.println("Successful" + successful);
	        } catch (Exception e) {
	            successful = false;
	        	e.printStackTrace();
	        }
		return successful;
	}
}