Core Java

Java jCIFS Samba File Access Example

In many enterprise environments, files are shared across systems using the SMB/CIFS protocol (commonly implemented by Samba on Linux). Java applications often need to read from or write to these shared folders. The JCIFS library provides a simple and reliable way to access Samba (SMB) shares directly from Java code without mounting them at the OS level. Let us delve into understanding Java JCIFS Samba file access.

1. Understanding the JCIFS Framework

JCIFS is a pure Java implementation of the SMB/CIFS networking protocol that enables Java-based applications to communicate with file-sharing services commonly used in Windows and Samba environments. By using JCIFS, developers can integrate network file system access directly into their applications without relying on platform-specific tools or native code.

It provides a high-level API to handle common file and directory operations over the network, making it suitable for enterprise applications, backend services, and automation tools that need to interact with shared drives securely and efficiently.

JCIFS allows Java applications to:

  • Connect to remote Samba or Windows file shares over a network
  • Authenticate using standard credentials such as username, password, and domain
  • Perform file and directory operations including read, write, rename, list, and delete
  • Access files using input and output streams, enabling efficient handling of large files
  • Integrate network file access seamlessly into existing Java workflows

2. Accessing Samba Shares from Java

2.1 Running a Samba Server Locally with Docker

For local development and testing, running Samba inside Docker is convenient. Below is a simple example using dperson/samba.

docker run -d \
  --name samba \
  -p 139:139 -p 445:445 \
  -v /tmp/samba-share:/mount \
  dperson/samba \
  -u "testuser;testpass" \
  -s "shared;/mount;yes;no;no;testuser"

This Docker command starts a Samba container in detached mode with the name “samba”, exposes ports 139 and 445 for SMB access, mounts the local directory /tmp/samba-share to /mount inside the container, creates a user named testuser with a password, and configures a shared folder called shared that is accessible to the specified user.

The SMB URL will look like:

smb://localhost/shared/

2.2 Implementing SMB File Operations Using JCIFS

// SambaJcifsExample.java
import jcifs.CIFSContext;
import jcifs.context.SingletonContext;
import jcifs.smb.NtlmPasswordAuthenticator;
import jcifs.smb.SmbFile;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class SambaJcifsExample {

    public static void main(String[] args) {
        try {
            // 1. Authentication
            NtlmPasswordAuthenticator auth =
                    new NtlmPasswordAuthenticator(null, "testuser", "testpass");

            CIFSContext baseContext = SingletonContext.getInstance();
            CIFSContext context = baseContext.withCredentials(auth);

            // Base Samba path
            String basePath = "smb://localhost/shared/";

            // 2. Create directory
            SmbFile directory = new SmbFile(basePath + "demo/", context);
            if (!directory.exists()) {
                directory.mkdir();
                System.out.println("Directory created: demo/");
            }

            // 3. Create and write file
            SmbFile file = new SmbFile(basePath + "demo/hello.txt", context);
            try (OutputStream os = file.getOutputStream()) {
                os.write("Hello from Java using JCIFS!".getBytes(StandardCharsets.UTF_8));
            }
            System.out.println("File written: hello.txt");

            // 4. Read file
            try (InputStream is = file.getInputStream()) {
                byte[] data = is.readAllBytes();
                System.out.println("File content:");
                System.out.println(new String(data, StandardCharsets.UTF_8));
            }

            // 5. List files in directory
            System.out.println("\nFiles in demo directory:");
            for (SmbFile f : directory.listFiles()) {
                System.out.println(" - " + f.getName());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.2.1 Code Explanation

This Java program demonstrates how to use the JCIFS library to authenticate with a Samba server, create a directory, write a file, read it back, and list files over SMB by first setting up NTLM credentials for a user, creating a CIFS context with those credentials, connecting to a shared Samba path, creating a folder if it does not exist, writing text to a file using an output stream, reading the file contents using an input stream, and finally listing all files present in the directory while handling any exceptions that may occur.

2.2.2 Program Output

Directory created: demo/
File written: hello.txt
File content:
Hello from Java using JCIFS!

Files in demo directory:
 - hello.txt

The output shows each major step of the program executing successfully against the Samba share. The message “Directory created: demo/” confirms that the application connected to the SMB share and created a new directory named demo. The message “File written: hello.txt” indicates that the Java program successfully created a file inside that directory and wrote text content to it. The “File content:” line followed by “Hello from Java using JCIFS!” verifies that the file was read back correctly from the Samba share, confirming that both write and read operations worked as expected. Finally, the list under “Files in demo directory:” displays hello.txt, showing that directory listing over SMB is functioning correctly.

3. Conclusion

JCIFS provides a powerful and flexible way to work with Samba (SMB/CIFS) shares directly from Java applications. By combining authentication, file operations, and stream-based access, you can build robust integrations without relying on OS-level mounts. For enterprise systems, batch processing, and integration services, JCIFS remains a practical and reliable solution for remote file access.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button