Java Program to Reading a Text File.

 
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadTextFile {
    public static void main(String[] args) {
        String filePath = "textfile.txt"; 
   // Replace with the actual path to your text file    
        
           try {
            File file = new File(filePath);
            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}


Java Program to Writing a Text File.

 
import java.io.FileWriter;
import java.io.IOException;

public class WriteTextFile {
    public static void main(String[] args) {
        String filePath = "output.txt"; 
        // Replace with the desired path and name of the output file

        try {
            FileWriter writer = new FileWriter(filePath);
            writer.write("Hello, World!");
            writer.close();
            System.out.println("Text file created successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



Java Program to append text to an existing file.

 
import java.io.FileWriter;
import java.io.IOException;

public class AppendTextToFile {
    public static void main(String[] args) {
        String filePath = "existingfile.txt"; 
        // Replace with the path and name of the existing file

        try {
            FileWriter writer = new FileWriter(filePath, true);
            writer.write("This is some appended text!");
            writer.close();
            System.out.println("Text appended successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Java Program to check if a file or directory specified by pathname exists or not

 

import java.io.File;

public class CheckFileOrDirectory {
    public static void main(String[] args) {
        String path = "path/to/file_or_directory"; 

        File file = new File(path);

        if (file.exists()) {
            System.out.println("File or directory exists.");
        } else {
            System.out.println("File or directory does not exist.");
        }
    }
}


index