Untitled

 avatar
unknown
java
a year ago
1.4 kB
5
Indexable
package readfile;

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

public class Readfile {

    public static void main(String[] args) {

        try {
            File obj = new File("theerdha2.txt");

            // Create the file only if it doesn't exist
            if (obj.createNewFile()) {
                System.out.println("File created: " + obj.getName());
            } else {
                System.out.println("File already exists.");
            }

            // Write to the file
            FileWriter nw = new FileWriter("theerdha2.txt");
            nw.write("It's a good file");
            nw.close(); // Close the FileWriter

            // Read from the file
            Scanner sobj = new Scanner(obj);
            while (sobj.hasNextLine()) {
                String data = sobj.nextLine(); // Use nextLine() instead of next()
                System.out.println(data);
            }
            sobj.close(); // Close the Scanner

        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        } finally {
            System.out.println("File operation completed.");
        }
    }
}
Editor is loading...
Leave a Comment