Working with File Data in Java

Working with File Data in Java

Reading and Writing files is a key task when working with applications. The main components responsible for this operation are the input and output streams. To make this process faster, NIO (New Input Output) had been introduced to Java with JDK 1.6. On top of the standard I/O streams, NIO allows more cumbersome processes to take place efficiently which is a requirement in all high-end web-based applications.

Reading a file in Java

To read any file in Java, you have to use the InputStream class. It is the superclass representing an input stream of bytes. The API that is most commonly used is the java.nio.files.

Example 1: To read a Text File

import java.nio.file.Files;
import java.nio.file,Paths;
String content = new String (Files.readAllBytes(Paths.get(fileName)));

Example 2: This example demonstrated how to read a text file line by line and store each line in a String type List

List <String> lines= Files.readAllLines (Path.get (fileName));
//Files.readAllLines uses UTF-8 character encoding

Example 3: Reading and Filtering

In this example, we will not only read each line but also perform a basic filtering option of removing white spaces at the end of lines as well as removing empty lines.

Files.lines(new File(“input.txt”).toPath()).map (s -> s.trim()).filter (s -. !s.isEmpty()).forEach ( System.out::println);

Example 4: Filtering out an expression if it matched with the given expression

Files.lines(new File(“input.txt”).toPath()).map (s -> s.trim()).filter (s -. !s.matches(“any_ranfom_expression”)).forEach ( System.out::println);

Example 5: Let us look at a concrete example where a line is extracted from a file and the prefix along with leading and trailing white spaces are removed. import;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;

public class ReadSampleProg
public static void main(String[] args) throws IOException
String versionString = readStreamOfLinesUsingFiles();
private static String readStreamOfLinesUsingFiles() throws IOException
Stream<String> lines = Files.lines(Paths.get("Hello World ", "SampleProgram.MF"));
Optional<String> versionString = lines.filter(s -> s.contains("Bundle-Version:")).map(e-> e.substring(15).trim()).findFirst();

if (versionString.isPresent())
return versionString.get();
return "";

Writing a File

If you want to write a file, use the following method:

Files.write(stateFile.toPath(), content.getBytes(StandardCharsets.UTF_8),StandardOpenOption.CREATE);



  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts


Leave a Reply

Your email address will not be published. Required fields are marked *

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