Skip to main content

I/O in Java - File Operations (Part 5)

In this post, we will look into the code for commonly used file operations one by one with code snippets. So without further ado, let's jump into the code straight away.

Create a file using java.io.File class

private static void createFileUsingFile(String path) {

        try {

            // Creating a new file at the given path with the name "file1.txt"
            File file = new File(path + "file1.txt");

            // The condition in if block returns true if the file is created
            if (file.createNewFile()) {
                System.out.println("New file is created!");
            } else {
                System.out.println("File already exists or some error occurred");
            }

            // Writing some content in the file
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write("Test data in " + file.getName());
            fileWriter.close();

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

Create a file using FileOutputStream

private static void createFileUsingFileOutputStream(String path) {

        try {
            // FileOutputStream instance
            FileOutputStream fileOutputStream = new FileOutputStream(path + "file2.txt");

            // Data to be written in the file
            String data = "Test data in file2.txt";

            // Writing data in the file after converting it into bytes
            fileOutputStream.write(data.getBytes());

            // Closing the instance
            fileOutputStream.close();

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

Create a file using NIO API

private static void createFileUsingNIO(String path) {

        // Data to be written in the file
        String data = "Test data in file3.txt";

        // Writing the data in the file after creating it
        try {
            Files.write(Paths.get(path + "file3.txt"), data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Read a file using BufferedReader

private static void readFileUsingBufferedReader(String path) {

        // Instance of BufferedReader
        BufferedReader bufferedReader = null;

        try {

            // Getting the instance of BufferedReader from the path of the file
            bufferedReader = new BufferedReader(new FileReader(path + "sample.txt"));

            // Variable that will read the file line by line
            String line;

            // Loop that will iterate the file line by line
            while ((line = bufferedReader.readLine()) != null) {

                // Reading the file and printing it
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Read file using try-with-resources block

private static void readFileUsingTryWithResources(String path) {

        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(path + "sample.txt"))) {

            // Variable to read file line by line
            String line;

            // Loop which will read the file line by line
            while ((line = bufferedReader.readLine()) != null) {

                // Printing the line on the console
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Read file using LineNumberReader

private static void readFileUsingLineNumberReader(String path) {

        LineNumberReader lineNumberReader = null;

        try {

            // Getting the LineNumberReader instance
            lineNumberReader = new LineNumberReader(new FileReader(path + "sample.txt"));

            // Print the initial line number
            System.out.println("Initial Line Number :: " + lineNumberReader.getLineNumber());

            // Setting the initial line number
            lineNumberReader.setLineNumber(4);
            System.out.println("New Initial Line Number :: " + lineNumberReader.getLineNumber());

            // Read all the lines wit their respective line numbers
            String line;

            while ((line = lineNumberReader.readLine()) != null) {
                System.out.println("Line-" + lineNumberReader.getLineNumber() + " :: " + line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (lineNumberReader != null) {
                    lineNumberReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Check file behaviour

private static void checkFileBehavior(String path) {

        String completePath = path + "sample.txt";

        // Check if file exists or not
        try {

            // Getting reference of file using path
            File file = new File(completePath);

            // Check if file exists
            if (file.exists()) {
                System.out.println("\nFile :: " + file.getName() + " exists");
            } else {
                System.out.println("\nFile :: " + file.getName() + " does not exist");
            }

            // Getting the "Path" object
            Path filePath = Paths.get(completePath);

            // Check if the file is readable
            if (Files.isReadable(filePath)) {
                System.out.println("\nFile :: " + file.getName() + " is readable");
            } else {
                System.out.println("\nFile :: " + file.getName() + " is not readable");
            }

            // Check if the file is writable
            if (Files.isWritable(filePath)) {
                System.out.println("\nFile :: " + file.getName() + " is writable");
            } else {
                System.out.println("\nFile :: " + file.getName() + " is not writable");
            }

            // Check if the file is executable
            if (Files.isExecutable(filePath)) {
                System.out.println("\nFile :: " + file.getName() + " is executable");
            } else {
                System.out.println("\nFile :: " + file.getName() + " is not executable");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Check if a certain word is present in the file

private static void checkIfWordPresent(String path) {

        // Reading file using Streams
        try (Stream<String> filteredLines = Files
                .lines(Paths.get(path, "sample.txt"))
                .onClose(() -> System.out.println("File is closed"))
                .filter(s -> s.contains("fermentum"))) {

            // Find first occurrence of "fermentum"
            Optional<String> hasWord = filteredLines.findFirst();

            // Print if the line which contains the word, if present
            hasWord.ifPresent(System.out::println);

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

Make a file read-only

private static void makeFileReadOnly(String path) {

        try {

            // Getting File instance
            File file = new File(path + "sample.txt");

            // Make file read only
            if (file.exists() && file.setReadOnly()) {
                System.out.println("\nFile :: " + file.getName() + " is set read only");
            } else {
                System.out.println("\nFile :: " + file.getName() + " cannot be set read only or some error occured");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Copy files using FileStreams

private static void copyUsingFileStreams(String path) {

        try {

            // Getting source and destination file reference using path
            File sourceFile = new File(path + "file1.txt");
            File destinationFile = new File(path + "file4.txt");

            // FileInputStream which will read the source file
            FileInputStream fileInputStream = new FileInputStream(sourceFile);

            if (destinationFile.createNewFile()) {

                // FileOutputStream for the destination file
                FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);

                // Buffer of size 1024 bytes
                byte[] buffer = new byte[1024];
                int readBytes;

                // Reading file content and write in the destination file
                while ((readBytes = fileInputStream.read(buffer)) > 0) {

                    fileOutputStream.write(buffer, 0, readBytes);
                }

                fileOutputStream.close();
            }

            fileInputStream.close();

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

Copy files using NIO Channel

private static void copyUsingNIOChannel(String path) {

        try {

            // Source file
            File sourceFile = new File(path + "file2.txt");
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            FileChannel sourceChannel = fileInputStream.getChannel();

            // Destination file
            File destinationFile = new File(path + "file5.txt");

            if (destinationFile.createNewFile()) {

                FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);
                FileChannel destinationChannel = fileOutputStream.getChannel();

                sourceChannel.transferTo(0, sourceFile.length(), destinationChannel);

                fileOutputStream.close();
            }

            fileInputStream.close();

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

Copy files using NIO Files class

private static void copyUsingNIOFiles(String path) {

        Path source = Paths.get(path + "file3.txt");
        Path destination = Paths.get(path + "file6.txt");

        try {

            Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);

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

Filter files using FilenameFilter class

private static void filterFilesUsingFilenameFiler(String path) {

        try {
            // Target directory
            File targetDirectory = new File(path);

            // Create few files with extension .log
            for (int i = 0; i < 5; i++) {
                File newFile = new File(path + "test" + i + ".log");
                if (newFile.createNewFile()) {
                    System.out.println("New file :: " + newFile.getName() + " is created");
                }
            }

            // Filter out all the files with .log extension
            String[] logFiles = targetDirectory.list((dir, name) -> name.endsWith(".log"));

            // List files
            Arrays.stream(Objects.requireNonNull(logFiles)).forEachOrdered(System.out::println);

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

Filter files using FileFilter class


private static void filterFilesUsingFileFilter(String path) {

        try {
            // Target directory
            File targetDirectory = new File(path);

            // Create few files with extension .log
            for (int i = 0; i < 5; i++) {
                File newFile = new File(path + "test" + i + ".json");
                if (newFile.createNewFile()) {
                    System.out.println("New file :: " + newFile.getName() + " is created");
                }
            }

            // List files using FileFilter
            FileFilter fileFilter = file -> file.getName().endsWith(".json");

            // List all the files
            File[] files = targetDirectory.listFiles(fileFilter);

            // List files
            for (File file : Objects.requireNonNull(files)) {
                System.out.println(file.getName());
            }

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

Conclusion

Today we saw various file operations along with their respective code snippets.

You can find the complete code on my GitHub repository.

I would love to hear your thoughts on this and would like have suggestions from you to make it better. 

Feel free to befriend me on FacebookTwitter or Linked In or say Hi by email.

Happy Coding 😊

Comments

Popular posts from this blog

Threads in Java - Masterclass (Part 0)

Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading.
One should exploit this feature, especially with all these multiple core machines nowadays.

Below are a few reasons why we should use multithreading -
1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a processor busy can be a tough task e…

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects -
making connectionscachingretrying failed requeststhreadingresponse parsingerror handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from https://timesofindia.indiatimes.com/rssfeedstopstories.cms using the Retrofit library.

To work with Retrofit, we need three classes -  Model class to map the JSON dataInterfaces which defines the possible HTTP operationsRetrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The response is returned as a Call object…

Material design profile page in Android

Hey everyone, some days back I was working on one my personal Android project. In that project, I was supposed to create a simple profile page for a user. This profile page was supposed to show some basic details of a user.

The output of this UI will be like this -
I created the profile page using material design and in this post, I am going to discuss a step by step tutorial to create a simple yet elegant profile page. Without further ado, let's get started.
Creating a new project Click on File ➤ New Project ➤ Empty Activity and fill the necessary details. Change styles.xml fileNavigate to app\src\main\res\values\styles.xmlChange the style value from DarkActionBar to NoActionBar as below<resources><!-- Base application theme. --><stylename="AppTheme"parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark&qu…