Warning: Undefined array key "HTTP_ACCEPT_LANGUAGE" in /home/bibiizjb/ptutorials.com/en/account/functions/check_point_2.php on line 25
Java File Handling (Reading/Writing Files) Tutorial

Java File Handling Tutorial

File handling in Java allows you to work with files and directories on your computer. Java provides a rich set of classes and methods in the java.io and java.nio packages to perform file operations such as reading, writing, creating, and deleting files. This tutorial will guide you through the basics of file handling in Java, including working with text files, binary files, and directories.

By the end of this tutorial, you'll understand how to perform common file operations in Java, making your programs capable of interacting with the file system.

File and Path Classes

The File class (from java.io) and the Path class (from java.nio.file) are used to represent files and directories in Java.

  • File Class:
    • Represents a file or directory path.
    • Provides methods for file operations like creating, deleting, and checking file properties.
  • Path Class:
    • Introduced in Java 7 as part of the NIO (New I/O) package.
    • Provides a more modern and flexible way to work with file paths.
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        // Using File class
        File file = new File("example.txt");
        System.out.println("File exists: " + file.exists());

        // Using Path class
        Path path = Paths.get("example.txt");
        System.out.println("Path: " + path.toAbsolutePath());
    }
}

Reading from a File

You can read data from a file using classes like FileReader, BufferedReader, and Scanner.

  • Using BufferedReader:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
            try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • Using Scanner:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            try (Scanner scanner = new Scanner(new File("example.txt"))) {
                while (scanner.hasNextLine()) {
                    System.out.println(scanner.nextLine());
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

Writing to a File

You can write data to a file using classes like FileWriter, BufferedWriter, and PrintWriter.

  • Using BufferedWriter:
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
            try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
                bw.write("Hello, World!");
                bw.newLine();
                bw.write("This is a new line.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • Using PrintWriter:
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    
    public class Main {
        public static void main(String[] args) {
            try (PrintWriter pw = new PrintWriter("output.txt"))) {
                pw.println("Hello, World!");
                pw.println("This is another line.");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

Working with Directories

You can create, delete, and list directories using the File and Files classes.

  • Creating a Directory:
    import java.io.File;
    
    public class Main {
        public static void main(String[] args) {
            File dir = new File("myDirectory");
            if (dir.mkdir()) {
                System.out.println("Directory created.");
            } else {
                System.out.println("Directory already exists.");
            }
        }
    }
  • Listing Files in a Directory:
    import java.io.File;
    
    public class Main {
        public static void main(String[] args) {
            File dir = new File("myDirectory");
            if (dir.isDirectory()) {
                String[] files = dir.list();
                for (String file : files) {
                    System.out.println(file);
                }
            }
        }
    }

Binary File Handling

For handling binary files, you can use FileInputStream and FileOutputStream.

  • Reading from a Binary File:
    import java.io.FileInputStream;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
            try (FileInputStream fis = new FileInputStream("example.bin"))) {
                int data;
                while ((data = fis.read()) != -1) {
                    System.out.print((char) data);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • Writing to a Binary File:
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
            try (FileOutputStream fos = new FileOutputStream("output.bin"))) {
                String text = "Hello, Binary World!";
                fos.write(text.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

This tutorial covered the basics of file handling in Java. Practice using these concepts to work with files and directories in your programs.

0 Interaction 0 Views 0 likes
Heart Button
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home