File Handling
File operations in Java allow you to perform various tasks related to reading, writing, creating, and manipulating files and directories. Java provides several classes and methods in the java.io
and java.nio
packages for these operations. Below are some common file operations in Java:
File and Directory Manipulation:
Creating a File or Directory:
File
class: UseFile
to create a new file or directory. You can check if a file or directory exists and create them if they don't.
File file = new File("example.txt"); if (!file.exists()) { file.createNewFile(); }
Deleting a File or Directory:
File
class: UseFile.delete()
to delete a file or an empty directory.
File file = new File("example.txt"); if (file.delete()) { System.out.println("File deleted successfully."); }
Listing Files in a Directory:
File
class: You can list files and directories in a directory usingFile.listFiles()
.
File directory = new File("myfolder"); File[] files = directory.listFiles(); if (files != null) { for (File file : files) { System.out.println(file.getName()); } }
File Input and Output:
Reading from a File:
FileInputStream
,BufferedReader
, orScanner
can be used to read data from a file.
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(); }
Writing to a File:
FileOutputStream
,BufferedWriter
, orPrintWriter
can be used to write data to a file.
try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) { writer.write("Hello, World!"); } catch (IOException e) { e.printStackTrace(); }
Working with Paths:
Using
Path
in Java NIO:Path
provides a more flexible way to work with file and directory paths.
Path path = Paths.get("example.txt"); System.out.println("File exists: " + Files.exists(path));
Creating Directories Recursively:
Use
Files.createDirectories()
to create directories and their parent directories if they do not exist.
Path path = Paths.get("parent/child/grandchild"); try { Files.createDirectories(path); } catch (IOException e) { e.printStackTrace(); }
Copying and Moving Files:
Copying a File:
Use
Files.copy()
to copy a file to another location.
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(); }
Moving/Renaming a File:
Use
Files.move()
to move or rename a file.
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(); }
These are some of the common file operations in Java. Depending on your specific requirements, you can choose the appropriate classes and methods to work with files and directories effectively.
Last updated
Was this helpful?