read and write text file in java code example

Example 1: writing to a text file java

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Example 2: java how to read a text file

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

class Scratch{
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File("filename"));
        input.next();       //returns next String
        input.nextLine();   //returns next Line
        input.nextBoolean();//returns next Boolean
        input.nextInt();    //returns next Int
        input.nextDouble(); //returns next double
        ...
    }
}

Tags:

Java Example