用java连接到windows中的共享文件夹

b4qexyjb  于 2023-06-28  发布在  Java
关注(0)|答案(3)|浏览(182)

我需要通过Java连接到远程Windows机器上的共享文件夹,在那里我把我的域身份验证(用户名和密码)放在代码中,下面是我的代码

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);  
    }

谢谢

pkmbmrz7

pkmbmrz71#

您应该使用SmbFileNtlmPasswordAuthentication from JCIFS。下面是一段简单的代码来告诉你如何做:

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());
}
bybem2ql

bybem2ql2#

如果您正在访问打开的共享文件夹(即用户名或密码未知或不需要),则可以按照以下代码操作:

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]);
}
w1jd8yoj

w1jd8yoj3#

自接受答案后,NtlmPasswordAuthentication已被弃用。因此,这是我解决的方法,例如,将文件复制到桑巴舞共享:

String user="your_samba_username";
String pass="your_samba_password";
String path="smb://samba_ip_address/outputdir/outputfile.txt";
try {
    InputStream  winfis = new FileInputStream(new File("c:/inputdir/inputfile.txt"));
    try {
        SingletonContext baseContext = SingletonContext.getInstance(); 
        Credentials credentials=new NtlmPasswordAuthenticator(null,user,pass); 
        CIFSContext testCtx = baseContext.withCredentials(credentials);
        try {             
            SmbFile smbFile = new SmbFile(path, testCtx);
            SmbFileOutputStream smbfos = new SmbFileOutputStream(smbFile);
            try {
                IOUtils.copy(winfis, smbfos);
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {    
                try {
                    smbfos.close();
                } catch (IOException ex) {
                     ex.printStackTrace();
                }
            }
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    } catch (CIFSException ex) {
        ex.printStackTrace();
    } finally {
        try {
            winfis.close();
        } catch (IOException ex) {
             ex.printStackTrace();
        }
    }
} catch (FileNotFoundException ex) {
    ex.printStackTrace();
}

所需的库(依赖项):

相关问题