Tuesday, April 30, 2013

Read a file in Java

Suppose we have a file file.txt with content like -
AAA|10
BB|36
CCCC|68

How we write a Java program to read the file and print out the sum of 10,36, and 68?

Example 1 - Use Scanner (Since 1.5)
package com.mqin.test;

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

public class ReadFileWithScanner {

    private final File file;
    private int sum = 0;

    public ReadFileWithScanner(String fileName) {
        file = new File(fileName);
    }

    public final void processFile() throws FileNotFoundException {
        Scanner scanner = new Scanner(new FileReader(file));
        try {
            while (scanner.hasNextLine()) {
                processLine(scanner.nextLine());
            }
        } finally {
            scanner.close();
        }
    }

    // Be open to use different way to process each line
    protected void processLine(String line) {
        Scanner scanner = new Scanner(line);
        scanner.useDelimiter("\\|");

        String string = scanner.next();
        int value = scanner.nextInt();
        sum += value;
        log(string + ":" + value);
    }

    private void printSum() {
        log("SUM:" + sum);
    }

    private static void log(Object o) {
        System.out.println(String.valueOf(o));
    }

    public static void main(String[] args) throws FileNotFoundException {
        ReadFileWithScanner rf = new ReadFileWithScanner("D:\\file.txt");
        rf.processFile();
        rf.printSum();
    }
}


Output
AAA:10
BB:36
CCCC:68
SUM:114

Example 2 - Use BufferedReader
package com.mqin.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileWithBufferedReader {

    private final File file;
    private int sum = 0;

    public ReadFileWithBufferedReader(String fileName) {
        file = new File(fileName);
    }

    public final void processFile() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                processLine(line);
            }
        } finally {
            br.close();
        }
    }

    // Use split to process each line
    protected void processLine(String line) {
        String[] array = line.split("\\|");
        sum += (new Integer(array[1])).intValue();
        log(array[0] + ":" + array[1]);
    }

    private void printSum() {
        log("SUM:" + sum);
    }

    private static void log(Object o) {
        System.out.println(String.valueOf(o));
    }

    public static void main(String[] args) throws IOException {
        ReadFileWithBufferedReader rf = new ReadFileWithBufferedReader("D:\\file.txt");
        rf.processFile();
        rf.printSum();
    }
}

Output
AAA:10
BB:36
CCCC:68
SUM:114

No comments:

Post a Comment