Some ways to read from and write into file (Java)

The examples demonstrate how can you write into a file using PrintWriter and Read from file using Scanner, etc.

1.

import java.io.*;

class A1{
    public static void main(String[] args) throws IOException{
        PrintWriter pw=new PrintWriter(“io.txt”);
        pw.println(“How are you?”);//pw.printf(“”)
        pw.println(“I am fine”);//pw.write(“”)
        pw.close();
    }
}

2.

import java.io.*;

class A2{
    public static void main(String[] args) throws IOException{
        PrintWriter pw=new PrintWriter(“io.txt”);
        pw.write(“How are you?”);
        pw.close();
    }
}

3.

import java.io.*;
import java.util.Scanner;

class A3{
    public static void main(String[] args) throws FileNotFoundException{
        Scanner in=new Scanner(new File(“io.txt”));
        while(in.hasNext()){
        System.out.println(in.next());
        }
    }
}

4.

import java.io.*;
import java.util.Scanner;

class A4{
    public static void main(String[] args) throws FileNotFoundException{
        Scanner in=new Scanner(new File(“io.txt”));
        while(in.hasNextLine()){
        System.out.println(in.nextLine());
        }
    }
}

5.

class A5{
    public static void main(String[] args){
    System.out.println(System.getProperty(“user.dir”));//to see current directory from where the program is executing
    }
}

6.
 //Reads from console
import java.util.Scanner;

class A6{
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        while(in.hasNextLine()){
            System.out.println(in.nextLine());
        }
    }
}