Java File I/O

Understanding modern input/output in Java

Binary Streams


  InputStream in = new FileInputStream("data.bin");
  OutputStream out = new FileOutputStream("copy.bin");
  
  in.transferTo(out);
    

Use for raw byte data (e.g., images, audio, files)

Character Streams


  Reader reader = new FileReader("text.txt");
  Writer writer = new FileWriter("copy.txt");
  
  int c;
  while ((c = reader.read()) != -1) {
      writer.write(c);
  }
    

Use for reading/writing text with proper encoding

File Tree (Recursive File Access)


  Path start = Paths.get("src");
  Files.walk(start)
       .filter(Files::isRegularFile)
       .forEach(System.out::println);
    
    src
   ├── App.java
   ├── utils
   │    └── Helper.java
   └── resources
        └── config.yml
    

Efficiently traverse directories

Watch Service (Directory Monitoring)


  WatchService watcher = FileSystems.getDefault().newWatchService();
  path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
  
  WatchKey key = watcher.take();
  for (WatchEvent event : key.pollEvents()) {
      System.out.println("Event: " + event.kind());
  }
    

Listen to file system changes in real time

Realtime I/O (Modern Java APIs)

  • UTF-8 by default (Java 18+)
  • Files.readString(), writeString()
  • HttpClient for reading web content
  • ImageIO.read(URL)
  • ZIP as FileSystem

  String content = Files.readString(Path.of("notes.txt"));
  Files.writeString(Path.of("copy.txt"), content);
    

Conclusion

  • Prefer NIO APIs over legacy IO
  • Use high-level methods: readString, walk, HttpClient
  • WatchService for real-time file changes
  • Stay away from File and BufferedReader