File Handling
File file = new File("example.txt"); if (!file.exists()) { file.createNewFile(); }File file = new File("example.txt"); if (file.delete()) { System.out.println("File deleted successfully."); }File directory = new File("myfolder"); File[] files = directory.listFiles(); if (files != null) { for (File file : files) { System.out.println(file.getName()); } }
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) { writer.write("Hello, World!"); } catch (IOException e) { e.printStackTrace(); }
Path path = Paths.get("example.txt"); System.out.println("File exists: " + Files.exists(path));Path path = Paths.get("parent/child/grandchild"); try { Files.createDirectories(path); } catch (IOException e) { e.printStackTrace(); }
Path source = Paths.get("source.txt"); Path target = Paths.get("target.txt"); try { Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); }Path source = Paths.get("oldfile.txt"); Path target = Paths.get("newfile.txt"); try { Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); }
Last updated