Problem :: One of my blog reader posted a problem that he cannot copy files over a network shared folder using java.
Solution :: Java alone doesn't have support for networked file sharing. But if you use a library, like Samba, then you can.
Solution :: Java alone doesn't have support for networked file sharing. But if you use a library, like Samba, then you can.
You can check below source code which successfully copies file from my local drive to a shared network folder ::
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package networkupload;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import jcifs.Config;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
/**
*
* @author ujjwal
*/
public class NetworkUpload {
public static void main(String[] args) throws IOException {
final String userName = "Ujjwal";
final String password = "ujjwal12345";
final String domain = "ujjwal12345";
//source path begins with / as i am using macbook (mac osx), in your case it will be windows drive path
final String sourcePath = "/Developer/test.pdf";
final String destinationPath = "smb://192.168.60.14/ftp/test.pdf";
copyFileUsingJcifs(domain,userName, password, sourcePath, destinationPath);
System.out.println("The file has been copied using JCIFS");
}
public static void copyFileUsingJcifs(final String domain,final String userName,
final String password, final String sourcePath,
final String destinationPath) throws IOException {
final NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
domain, userName, password);
final SmbFile sFile = new SmbFile(destinationPath, auth);
final SmbFileOutputStream smbFileOutputStream = new SmbFileOutputStream(
sFile);
final FileInputStream fileInputStream = new FileInputStream(new File(
sourcePath));
final byte[] buf = new byte[16 * 1024 * 1024];
int len;
while ((len = fileInputStream.read(buf)) > 0) {
smbFileOutputStream.write(buf, 0, len);
}
fileInputStream.close();
smbFileOutputStream.close();
}
}
If you face any issues implementing this code, you can contact me ::
Cheers,
Ujjwal Soni