Click here to Skip to main content
15,885,309 members
Articles / Programming Languages / Java

Working with Shared Files in Remote Server using SMB in Java

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Mar 2020CPOL2 min read 20.6K   1  
A demo to show reading resources in the remote server using SMB protocol
This is a demonstration of a use case where an application needs to interact with shared files in Windows server machines using a simple Java application.
This is an old version of the currently published technical blog.

Introduction

We are used to working with shared files where sharing is limited to users either in some domain to certain users. The remote application needs to access the shared resource and take actions such as add, delete resources in the shared location.

A server has shared resources that typically uses the Server Message Block (SMB) protocol (Server Message Block)in the Windows machine. The SMB protocol enables an application to access files on the remote servers, as well as other resources allowing a client application to open, read, move, update files on the remote server. The resource is limited to certain users. The user needs to pass credentials to access the shared resource. The activities that the user can do on the shared resource is defined in the sharing permission. Let's assume that the user has both read and write permission.

In this article, I am demonstrating a use case where an application needs to interact with shared files in Windows server machines using a simple Java application. The use case makes the following assumption:

  • The server is a Windows machine.
  • There exists a local user named 'Test' and the password for the user is 'Password'.
  • The shared location is '127.0.0.0.1\temp'.
  • The user 'Test' has access to the shared location 'temp' which can be anywhere in the machine that has IP of '127.0.0.1'.
  • The client application has access to the network.

CodeBase

The application that we are designing is in Java using Maven for build and dependency management. I am using JCIFS, an open-source client library that implements the CIFS/SMB networking protocol (https://www.jcifs.org/). The library is available from Maven Repository (https://mvnrepository.com/artifact/jcifs/jcifs/1.3.17).

The dependencies are shown in the following pom.xml file:

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>fileShare</groupId>
    <artifactId>fileShare</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>jcifs</groupId>
            <artifactId>jcifs</artifactId>
            <version>1.3.17</version>
        </dependency>
    </dependencies>
</project>

Currently, the application has one file Main.java with the following content:

Java
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import java.net.MalformedURLException;

public class Main {
    public static void main(String[] args) {
        String url = "smb://127.0.0.1/test/";
        String userName = "test";
        String password = "password";
        String domain = null;
        NtlmPasswordAuthentication auth = 
              new NtlmPasswordAuthentication(null, userName, password);
        try {
            doRecursiveLookup(new SmbFile(url, auth));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    /*
    * Recursively scans through the folder for files and prints the name of folder and file
    */
    public static void doRecursiveLookup(SmbFile smb) {
        try {
            if (smb.isDirectory()) {
                System.out.println(smb.getName());
                for (SmbFile f : smb.listFiles()) {
                    if (f.isDirectory()) {
                        doRecursiveLookup(f);
                    } else {
                        System.out.println("\t:" + f.getName());
                    }
                }
            } else {
                System.out.println("\t:" + smb.getName());
            }
        } catch (SmbException e) {
            e.printStackTrace();
        }
    }
}

Here, the main method uses a url pattern of for smb protocol and points to shared location at line 8. Local variables for userName, password and domains are initialized in lines 9 through 11 and authenticates the user in line 13 at which time, the application has successfully connected to the shared folder.

The application creates a SmbFile object in line 15 and passes that folder to a method called doRecursiveLookup(..) in line 24. The method simply iterates through all the files and folders within the shared location and prints the names in the console in a recursive fashion. Note that the SmbFile object is the same for file or folders and .isDirectory() method was used to test if the object in scope is file or folder.

In the demo, I showed reading the resources in the remote server using SMB protocol.

Additional Resources

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
United States United States
Benktesh is a senior software engineer at Sony where he is a software developer/architect. His main focus when coding is quality, simplicity, and scalability and he is experienced in a broad range of subjects (software design, software development process, project management, testing, UI, multithreading, database, mobile development, and more).

Outside of professional work, there are always some side projects he is working on such as simulation modeling of financial, energy and emissions data and writing articles both technical and non-technical (see his blog at https://benktesh.blogspot.com/). While not coding, he is either reading books fiction and/or non-fiction, watching tv shows, trading stocks, and discussing climate change, global warming, emission trading, and traveling to meet people, place, and culture.

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.