4

パフォーマンス最適化の観点から: Java でのファイルの読み取り - バッファー付きリーダーとスキャナーのどちらが優れていますか?

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;


public class BufferedReaderExample {   

    public static void main(String args[]) {

        //reading file line by line in Java using BufferedReader       
        FileInputStream fis = null;
        BufferedReader reader = null;

        try {
            fis = new FileInputStream("C:/sample.txt");
            reader = new BufferedReader(new InputStreamReader(fis));

            System.out.println("Reading File line by line using BufferedReader");

            String line = reader.readLine();
            while(line != null){
                System.out.println(line);
                line = reader.readLine();
            }           

        } catch (FileNotFoundException ex) {
            Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);

        } finally {
            try {
                reader.close();
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
  } 

Output:
Reading File line by line using BufferedReader
first line in file
second line
third line
fourth line
fifth line
last line in file

スキャナーの他のアプローチは..

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

/**
 * @author Javin Paul
 * Java program to read file line by line using Scanner. Scanner is a rather new
 * utility class in Java and introduced in JDK 1.5 and preferred way to read input
 * from console.
 */
public class ScannerExample {


    public static void main(String args[]) throws FileNotFoundException  {

       //Scanner Example - read file line by line in Java using Scanner
        FileInputStream fis = new FileInputStream("C:/sample.txt");
        Scanner scanner = new Scanner(fis);

        //reading file line by line using Scanner in Java
        System.out.println("Reading file line by line in Java using Scanner");

        while(scanner.hasNextLine()){
            System.out.println(scanner.nextLine());
        }

        scanner.close();
    }   

}

Output:
Reading file line by line in Java using Scanner
first line in file
second line
third line
fourth line
fifth line
last line in file
4

1 に答える 1

6

BufferedReaderファイルから文字を読み取るたびにファイルにアクセスする必要がないScannerため、はるかに高速です。buffers the character

スキャナは、プリミティブ データ型を直接読み取るなどの特定の用途に使用され、正規表現にも使用されます。

Scanner と BufferedReader の両方を使用しましたが、BufferedReader は非常に高速なパフォーマンスを提供します。自分でもテストできます。

于 2012-08-15T09:27:10.447 に答える