Different ways of Read and Write (Input/Output ) a file in Java

Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2020-10-02 14:55:29 Viewed : 611


Different ways of Read and Write (Input/Output ) a file in Java

 

 Package java.io

Provides for system input and output through data streams, serialization and the file system. Unless otherwise noted, passing a null argument to a constructor or method in any class or interface in this package will cause a NullPointerException to be thrown.

1. Reading and wrting a file example   

 

java.nio.file.Files

 

This class consists exclusively of static methods that operate on files, directories, or other types of files.

In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.

Since:

1.7

Path java.nio.file.Files.write(Path path, byte[] bytes, OpenOption... options) throws IOException

 

ReadAndWrite.java

package runnerdev.io.file;

 

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

import java.util.List;

 

public class ReadAndWrite {

            public static void main(String[] args) throws IOException {

                        String filePath"C:/Downloads/runnerdev/java/";

                        String input = readTextFile(filePath + "readTestFile.txt");

 

                        writeToTextFile(filePath + "writeCopy.txt", input);

                        readTextFile(filePath + "writeCopy.txt");

 

                        readTextFileByLines(filePath + "readTestFile.txt");

                        Path path = Paths.get(filePath + "readTestFile.txt");

                        path.getFileName().compareTo(path.getFileName());

            }

 

            public static String readTextFile(String fileName) throws IOException {

                        String readTextFile = new String(Files.readAllBytes(Paths.get(fileName)));

                        System.out.println("readTextFileByLines: " + readTextFile);

                        return readTextFile;

            }

 

            public static List<String> readTextFileByLines(String fileName) throws IOException {

                        List<String> readLines = Files.readAllLines(Paths.get(fileName));

                        System.out.println("readTextFileByLines: " + readLines);

                        return readLines;

            }

 

            public static void writeToTextFile(String fileName, String writeData) throws IOException {

                        Files.write(Paths.get(fileName), writeData.getBytes(), StandardOpenOption.CREATE);

                        System.out.println("writeToTextFile is done");

            }

 

}

OutPut:

2. Using BufferedReader

java.io.BufferedReader.BufferedReader(Reader in)

Creates a buffering character-input stream that uses a default-sized input buffer

The try-with-resources Statement

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

JDK 1.7 try-with-resources to auto close the resources

 static String readFirstLineFromFile(String path) throws IOException {

    try (BufferedReader br =

                   new BufferedReader(new FileReader(path))) {

        return br.readLine();

    }

 

 

 

ReadFileWithTryResource.java

package runnerdev.io.file;

 

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

 

public class ReadFileWithTryResource {

 

            public static void main(String[] args) {

                        String filePath = "C:Downloads unnerdevjava";

 try (FileReader reader = new FileReader(filePath+"readTestFile.txt");

                                                BufferedReader br = new BufferedReader(reader)) {

             

                                    String line;

                                    while ((line = br.readLine()) != null) {

                                                System.out.println(line);

                                    }

 

                        } catch (IOException e) {

                                    System.err.format("IOException: %s%n", e);

                        }

            }

 

}

 

Output:

thank you for downloading project from runnerdev.com

ReadAndWrite example

3. Read files from directroy

Stream<Path> java.nio.file.Files.walk(Path start, FileVisitOption... options) throws IOException

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

This method works as if invoking it were equivalent to evaluating the expression:

 walk(start, Integer.MAX_VALUE, options)

ReadFilesFromDir.java

 

package runnerdev.io.file;

 

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Paths;

 

public class ReadFilesFromDir {

 

            public static void main(String[] args) {

            String filePath =  "C:/Downloads/runnerdev/java/";

                        try {

Files.walk(Paths.get(filePath)).filter(Files::isRegularFile).forEach(System.out::println);

                        } catch (IOException e) {

                                    e.printStackTrace();

                        }

            }

}

4. Deleting a directory with all subdirectories and files

package runnerdev.io.file;

 

import java.io.File;

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Path;

import java.util.Comparator;

 

public class DeleteFile {

 

            public static void main(String[] args) {

            String filePath "C:/Downloads/runnerdev/java/";

                        try {

                                    Path path = new File(filePath).toPath();                      Files.walk(path).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);

                        } catch (IOException e) {

                                    e.printStackTrace();

                        }

            }

 

}

 

5. Check if a file exists

FileExist.java

 

package runnerdev.io.file;

 

import java.io.File;

 

public class FileExist {

 

     public static void main(String[] args) {

           String filePath "C:/Downloads/runnerdev/java/testFile.txt";

           File f = new File(filePath);

           if (f.exists() && !f.isDirectory()) {

                System.out.println("File is existed!!");

           } else {

                System.out.println("File is not existed!!");

           }

 

     }

 

}

6. Compare two file paths

package runnerdev.io.file;

 

import java.io.File;

 

public class CompareFile {

 

            public static void main(String[] args) {

 

                        String filePath "C:/Downloads/runnerdev/java/";

                        File file1 = new File(filePath + "readTestFile.txt");

                        File file2 = new File(filePath + "readTestFile.txt"");

                        if (file1.compareTo(file2) == 0) {

                                    System.out.println("Both the paths are  equal");

                        } else {

                                    System.out.println("Both the paths are not equal");

                        }

            }

}

Output:

 Both the paths are   equal

7. Remove white Space from fileNames and comapre fileNames

RemoveWhiteSpace.java

import java.io.File;

import java.nio.file.Path;

import java.nio.file.Paths;

 

public class RemoveWhiteSpace {

 

            public static void main(String[] args) {

                        String fileName1 = "ReadTestFile.txt";// get fileName from database

                        String folderFilePath = "C:/Users/Downloads/runnerdev/test/";

                        removeWhiteSpace(folderFilePath);

                        Path path = Paths.get(folderFilePath + "readTestFile.txt");// localFileName

                        String fileName = path.getFileName().toString();

                        fileName1 = fileName1.toString();

                        System.out.println("fileName:" + fileName);

                        System.out.println("fileName1:" + fileName1);

 

                        /*** Below logic is used to compare the file Names. */

                        if (fileName.equalsIgnoreCase(fileName1)) {

                                    System.out.println("FileNames are matched");

                        } else {

                                    System.out.println("FileNames are not matched");

                        }

            }

 

            /*** Below logic is used to remove the white space from the file Names. */

 

            static void removeWhiteSpace(String folderFilePath) {

                        File folderFiles = new File(folderFilePath);

System.out.println("folderFiles=>" + folderFiles + " folderFiles.listFiles()=>" + folderFiles.listFiles());

 

                        try {

                                    if (folderFiles.listFiles() != null) {

                                                for (File old : folderFiles.listFiles()) {

                                                            String oldName = old.getName();

                                                            System.out.println("OldFileName is: " + oldName);

                                                            if (!oldName.contains(" "))

                                                                        continue;

                                                            String newName = oldName.replaceAll("s", "");

                                                            old.renameTo(new File(folderFiles + "/" + newName));

                                                  System.out.println("renameTo NewFileName: " + newName);

                                                }

                                    }

                        } catch (Exception e) {

                                    e.printStackTrace();

                        }

 

            }

}

7. Remove white Space from fileNames  

RemoveWhiteSpace.java

import java.io.File;

import java.nio.file.Path;

import java.nio.file.Paths;

 

public class RemoveWhiteSpace {

 

            public static void main(String[] args) {

                       

                        String folderFilePath = "C:/Users/Downloads/runnerdev/test/";

                        removeWhiteSpace(folderFilePath);

            }

 

            /*** Below logic is used to remove the white space from the file Names. */

 

            static void removeWhiteSpace(String folderFilePath) {

                        File folderFiles = new File(folderFilePath);

System.out.println("folderFiles=>" + folderFiles + " folderFiles.listFiles()=>" + folderFiles.listFiles());

 

                        try {

                                    if (folderFiles.listFiles() != null) {

                                                for (File old : folderFiles.listFiles()) {

                                                            String oldName = old.getName();///read T est File.txt

                                                            System.out.println("OldFileName is: " + oldName);

                                                            if (!oldName.contains(" "))

                                                                        continue;

                                                            String newName = oldName.replaceAll("s", "");//

                                                            old.renameTo(new File(folderFiles + "/" + newName));

                                                  System.out.println("renameTo NewFileName: " + newName);

                                                }

                                    }

                        } catch (Exception e) {

                                    e.printStackTrace();

                        }

 

            }

}

OutPut :

folderFiles=>C:UsersDownloads unnerdev est folderFiles.listFiles()=>[Ljava.io.File;@15db9742

OldFileName is: read T est File.txt

renameTo NewFileName: readTestFile.txt

 

8. Compare two fileNames:

public class comapreFileNames {

 

            public static void main(String[] args) {

 

                     /*** Below logic is used to compare the file Names. */

 

                        String fileName1 = "ReadTestFile.txt";// get fileName from database

 

                        Path path = Paths.get(folderFilePath + "readTestFile.txt");// localFileName

                        String fileName = path.getFileName().toString();

                        fileName1 = fileName1.toString();

                        System.out.println("fileName:" + fileName);

                        System.out.println("fileName1:" + fileName1);

 

           

                        if (fileName.equalsIgnoreCase(fileName1)) {

                                    System.out.println("FileNames are matched");

                        } else {

                                    System.out.println("FileNames are not matched");

                        }

}

}

Output:

fileName:readTestFile.txt

fileName1:ReadTestFile.txt

FileNames are matched


Search
Related Articles

Leave a Comment: