eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

Cross-platform file exchange capabilities are crucial for the operation of computer networks. We can provide them with the Server Message Block (SMB) protocol and its widespread open-source implementation, Samba.

In this tutorial, we’ll learned how to access Samba resources from Java, without the need to mount or map a network drive.

2. The JCIFS library

Common Internet File System (CIFS) is a dialect of SMB. We’ll use the codelibs JCIFS implementation, which supports the newest SMB3 protocol.

Let’s add it with the Maven dependency:

<dependency>
    <groupId>org.codelibs</groupId>
    <artifactId>jcifs</artifactId>
    <version>3.0.1</version>
</dependency>

3. Setting up a Samba Server

Throughout this tutorial, we’ll use the Samba server set up in a VirtualBox guest machine. As a guest, we chose the Ubuntu server.

Next, let’s configure the VirtualBox host-only network adapter. Then, we narrow the DHCP address range to a single IP address: 192.168.56.101. This trick spares us a more sophisticated static IP setting.

During installation of the guest system, let’s add user jane. Afterward, we need to install Samba and add jane to the Samba users:

$ sudo smbpasswd -a jane

We need two folders for the shares:

$ mkdir /srv/samba/public /srv/samba/sambashare

To expose the folders, we set the 777 permission on them:

$ sudo chmod 777 /srv/samba/public /srv/samba/sambashare

Now, let’s edit the /etc/samba/smb.conf file:

$ sudo nano /etc/samba/smb.conf

Then we add two sections for shares:

[publicshare]
   comment = Anonymous Samba share
   path = /srv/samba/public
   read only = no
   guest ok = yes
   guest only = yes

[sambashare]
   comment = Samba on Ubuntu
   path = /srv/samba/sambashare
   read only = no
   browsable = yes

This way we created two Samba shares: an anonymous publicshare and a password-protected sambashare.

4. Simple Example

Let’s run a simple code to see the basics of reaching a Samba share. We’ll check a file located on publicshare:

// Default context
CIFSContext context = SingletonContext.getInstance();

LOGGER.info("#  Checking if file exists");
try (SmbFile file = new SmbFile("smb://192.168.56.101/publicshare/test.txt", context)) {
    if (file.exists()) {
        LOGGER.info("File " + file.getName() + " found!");
    } else {
        LOGGER.info("File " + file.getName() + " not found!");
    }
}

We can note elements necessary to establish the communication:

  • CIFSContext maintains client configuration, credentials, and other related information. Here, it’s an instance of SingletonContext, which provides credentials suitable for an anonymous account
  • SmbFile, which represents any kind of Samba resource. In our case, this is a file. We can place it into a try-with-resource block

Finally, we used the exists() method on the file object.

5. Authentication

We can create the CIFSContext object with credentials. Let’s list elements in the password-protected share sambashare:

NtlmPasswordAuthenticator credentials = new NtlmPasswordAuthenticator(
    "WORKGROUP",    // Domain name
    "jane",         // Username
    "Test@Password" // Password
);

// Context with authentication
CIFSContext authContext = context.withCredentials(credentials);

LOGGER.info("# Logging in with user and password");
try (SmbFile res = new SmbFile("smb://192.168.56.101/sambashare/", authContext)) {
    for (String element : res.list()) {
        LOGGER.info("Found element " + element);
    }
}

First, we created the NtlmPasswordAuthenticator object to store credentials. Then, we called the method withCredentials() on the existing context object. As a result, we obtained a child authContext with our credentials. Finally, the list() function showed all components of the share.

6. Working With Files and Directories

JCIFS provides a comprehensive set of functions for operating on files and folders. Let’s take a look at some of them.

6.1. Listing and Checking Files

With listFiles(), we can list files and folders. It returns an SmbFile object, which allows the use of many verification functions:

LOGGER.info("# List files and folders in Samba share");
try (SmbFile res = new SmbFile("smb://192.168.56.101/publicshare/", context)) {
    for (SmbFile element : res.listFiles()) {
        LOGGER.info("Found Samba element of name: " + element.getName());
        LOGGER.info("    Element is file or folder: " + (element.isDirectory() ? "file" : "folder"));
        LOGGER.info("    Length: " + element.length());
        LOGGER.info("    Last modified: " + new Date(element.lastModified()));
    }
}

In this example, we iterated through all items in the public folder. We determined whether it’s a file or a directory using the isDirectory() method. Next, we retrieved its length and modification time with the length() and getLastModified() methods, respectively.

6.2. Creating and Deleting Files

The JCFIS library allows creation and deletion of both files and directories. First, let’s work with files. We’ll create and immediately delete the New_file.txt file:

LOGGER.info("# Creating and deleting a file");
String fileName = "New_file.txt";
try (SmbFile file = new SmbFile("smb://192.168.56.101/publicshare/" + fileName, context)) {
    LOGGER.info("About to create file " + file.getName() + "!");
    file.createNewFile();

    LOGGER.info("About to delete file " + file.getName() + "!");
    file.delete();
}

We created an SmbFile object for a yet non-existent file. Then, we called its createNewFile() method. Finally, we applied the delete() function to remove the file. Notably, createNewFile() skips existing files without notification.

6.3. Creating and Deleting Folders

We can deal with folders in a similar way:

LOGGER.info("# Creating and deleting a folder");
String newFolderName = "New_folder/";
try (SmbFile newFolder = new SmbFile("smb://192.168.56.101/publicshare/" + newFolderName, context)) {
    LOGGER.info("About to create folder " + newFolder.getName() + "!");
    newFolder.mkdir();

    LOGGER.info("About to delete folder " + newFolder.getName() + "!");
    newFolder.delete();
}

We use the mkdir() method to create the folder and the delete() method to remove it. In the folder case, we must ensure that the folder doesn’t exist; otherwise, mkdir() will fail.

Let’s note that we should take great care when removing a folder with delete(). This method traverses and deletes the entire folder tree, with all files. Moreover, it’s able to remove the read-only permission on files.

In addition, we can create a whole directory tree with the mkdirs() method:

LOGGER.info("# Creating and deleting a subfolder with parent");
newFolderName = "New_folder/";
String subFolderName = "New_subfolder/";
try (SmbFile newSubFolder = new SmbFile("smb://192.168.56.101/publicshare/" + newFolderName + subFolderName, context)) {
    LOGGER.info("About to create folder " + newSubFolder.getName() + "!");
    newSubFolder.mkdirs();
}

We created a new directory, New_subfolder, along with the previously non-existent parent folder, New_folder.

6.4. Copying Files

The copyTo() method facilitates copying files and directories. We can use it on a single file or a folder. Let’s copy the entire contents of sambashare to publicshare:

LOGGER.info("# Copying files with copyTo");
try (SmbFile source = new SmbFile("smb://192.168.56.101/sambashare/", authContext); //needs authentication
    SmbFile dest = new SmbFile("smb://192.168.56.101/publicshare/", context)) { //public share
    source.copyTo(dest);
}

We copy by calling copyTo() on the Samba resource source and passing the destination resource dest to this method. Notably, these resources are different Samba shares.

We can also copy files between different servers. However, we cannot copy from the local filesystem, only between resources managed by Samba.

7. Working With Streams

The library provides SmbFileInputStream and SmbFileOutputStream, which override the standard Java InputStream and OutputStream abstract classes, respectively. Let’s copy a local file to the Samba share:

LOGGER.info("# Copying files with streams");
try (InputStream is = new FileInputStream("/home/joe/test.txt"); //Local file
     SmbFile dest = new SmbFile("smb://192.168.56.101/publicshare/test_copy.txt", context); //Samba resource
     OutputStream os = dest.getOutputStream()) {

    byte[] buffer = new byte[65536]; // using 64KB buffer
    int bytesRead;
    while ((bytesRead = is.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);
    }
}

We read the local file with FileInputStream. Then, we copy content using an internal buffer. This method complements the copyTo() method when local files are in play.

8. Conclusion

In this article, we learned how to access Samba resources with the JCIFS library. For tests, we set up a simple Samba server. Then, we examined a shared resource and briefly learned about Samba authentication.

Then we focused on the file operations. First, we listed files and folders and checked their properties. Next, we performed create, copy, and delete operations on both files and directories. Finally, we used the JCIFS implementation of Java I/O streams to read and write Samba files.

As always, the code for the examples is available over on GitHub.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments