Untitled

 avatar
unknown
java
a year ago
1.2 kB
6
Indexable
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");

           
            if (obj.createNewFile()) {
                System.out.println("File created: " + obj.getName());
            } else {
                System.out.println("File already exists.");
            }

           
            FileWriter nw = new FileWriter("theerdha2.txt");
            nw.write("welcome to my file");
            nw.close(); 

          
            Scanner sobj = new Scanner(obj);
            while (sobj.hasNextLine()) {
                String data = sobj.nextLine();
                System.out.println(data);
            }
            sobj.close(); 

        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        } finally {
            System.out.println("Successfully created a file.");
        }
    }
}


    



Editor is loading...
Leave a Comment