How to read and manipulate values from text file by using java code

First of all create a text file and call it "txtFile.txt", now add the following values into the text file.

10
50.1
Amzi

Now, create a java class into the same folder where you have stored the txtFile.txt
The java class will be as follows.

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

public class ManipulateTxtfile {

    public static void main(String[] args) {
        try {
            Scanner in = new Scanner(
                    new File("txtFile.txt"));
            int first = in.nextInt();
            double second = in.nextDouble();
            String name = in.next();
            double sum = first + second;
            System.out.println("Hello " + name + "\nThe sum of " + first
                    + " and " + second + " is = " + sum);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}


The output of the above program will look something like this:

Hello Amzi
The sum of 10 and 50.1 is = 60.1

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete