28

I need to connect to a shared folder on a remote windows machine through java , where i put my domain authentication (username and password ) in the code , here is my code

 File file = new File("\\\\theRemoteIP\\webapps");   
    File[] files = file.listFiles();  
    System.out.println("access done");  

    for (int i = 0; i < files.length; i++)  
    {  
        String name = files[i].getName();  
        System.out.println(name);  
    }  

Thanks

Andrea
  • 6,032
  • 2
  • 28
  • 55
SShehab
  • 1,039
  • 3
  • 17
  • 31

2 Answers2

39

You should use SmbFile and NtlmPasswordAuthentication from JCIFS. Here is a simple piece of code to show you how to do :

String url = "smb://yourhost/yourpath/";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, "user", "password");
SmbFile dir = new SmbFile(url, auth);
for (SmbFile f : dir.listFiles())
{
    System.out.println(f.getName());
}
Valentin Rocher
  • 11,667
  • 45
  • 59
  • NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, "user", "password"); So the "user" , "password" are the domain authentication right ? – SShehab Feb 16 '10 at 08:47
  • that's it. See the javadoc (linked in the answer) for more details. – Valentin Rocher Feb 16 '10 at 10:24
  • 3
    If you're using a [UNC path](https://en.wikipedia.org/wiki/Path_(computing)#Universal_Naming_Convention), make sure to have two extra forward slashes to indicate that it is a UNC path. For example `smb:////11.1.2.10/myFolder` or `smb:////myShare/myFolder` – Brad Turek May 27 '20 at 00:13
2

If you are accessing open shared folders (i.e. username or password are not known or required),then you can follow the code below :

String path="smb://172.16.0.11/";

SmbFile smbFile = new SmbFile(path);
String a[]=smbFile.list();
for(int i=0;i<a.length;i++)
{
    System.out.println(a[i]);
}
avi
  • 21
  • 2