Java - Files and I/O


Java I/O is basically provide java API to read and write data to input and output resources.
IO operations are costly because IO devices are shared between different threads and also put an impact on performance as well.


Please visit oracle docs for details:-

Reading a file:-

Java 8 nio package provide rich IO features, for details visit oracle docs: - https://docs.oracle.com/javase/8/docs/technotes/guides/io/index.html

See below code snippet:-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
 * Reading a file
 * @author Manoj
 */
public class Test {

   public static void main(String[] args) {
     try {
       String content = new String(Files.readAllBytes(Paths.get("/test.txt")));
       System.out.println(content);
    } catch (IOException e) {
       System.out.println(e.getMessage());
     }
   }
}
Files.readAllLines uses UTF-8 character encoding. It also ensures that file is closed after all bytes are read or in case an exception occurred.


import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

/**
 * Reading a file with filtering empty lines
 * @author Manoj
 */
public class Test {

  public static void main(String[] args) {
    try {
     Files.lines(new File("test.txt").toPath()).filter(s -> !s.isEmpty())
     .forEach(System.out::println);
     } catch (IOException e) {
       System.out.println(e.getMessage());
     }
   }
}


/**
 * To print the current directory of java files
 * @author Manoj
 */
public class Test {
  public static void main(String[] args) {
     System.out.println(System.getProperty("user.dir"));
  }
}


Reading a file from resource folder –

public void getResourceFile(){
  ClassLoader classLoader = getClass().getClassLoader();
  File file = new File(classLoader.getResource("file/test.xml").getFile());
  try (Scanner scanner = new Scanner(file)) {
     while (scanner.hasNextLine()) {
        System.out.println(scanner.nextLine());
     }
  } catch (FileNotFoundException e) {
     System.out.println(e.getMessage());
  }
}


Writing a file

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * Reading and writing into a files
 * @author Manoj
 */
public class Test {
  public static void main(String[] args) {
    try {
     String content = new String(Files.readAllBytes(Paths.get("Test.txt")));
     Files.write(Paths.get("Test2.txt"), content.getBytes(), StandardOpenOption.CREATE);
     } catch (IOException e1) {
           System.out.println(e1.getMessage());
     }
  }
}

1 comment: