FileInputStream vs BufferedInputStreamAdvertisement特徴読み込みJavaで入出力を実現するクラスreader, writer, input, outputはバイト単位・文字単位で入出力を行うため、そのまま使用すると効率が悪い。バッファリング前述のreader, writer, input, outputにはバッファリングを行うクラスが用意されており、これを使用することにより効率の良い入出力を行うことができる。比較プログラム
プログラム実行時にファイル名(ファイルパス)を受け取り、そのファイル内の文字数をカウントするプログラムで比較。
バッファを使用しない。
import java.awt.*;
import java.io.*;
public class BufferTestA{
public static void main(String[] args) throws IOException{
CountChar cc = new CountChar();
Vector log = new Vector();
long startTime = System.currentTimeMillis();
for(int i = 0; i < args.length; ++i){
cc.count(args[i]);
}
long endTime = System.currentTimeMillis();
System.out.println("");
System.out.println((endTime - startTime) + " msec");
}
}
class CountChar{
public void count(String filename) throws IOException{
System.out.print(filename + " have ");
FileInputStream fis = new FileInputStream(filename);
int tmp;
long count = 0;
while((tmp = fis.read()) != -1){
char c = Character.toLowerCase((char)tmp);
int pos = c - 'a';
if((pos >= 0) && (pos <= 25)){
count++;
}
}
fis.close();
System.out.println(count + " characters");
}
}
バッファを使用する。
import java.awt.*;
import java.io.*;
import java.util.*;
public class BufferTestB{
public static void main(String[] args) throws IOException{
CountChar cc = new CountChar();
Vector log = new Vector();
long startTime = System.currentTimeMillis();
for(int i = 0; i < args.length; ++i){
cc.count(args[i]);
}
long endTime = System.currentTimeMillis();
System.out.println("");
System.out.println((endTime - startTime) + " msec");
}
}
class CountChar{
public void count(String filename) throws IOException{
System.out.print(filename + " have ");
BufferedInputStream bis =
new BufferedInputStream(new FileInputStream(filename));
int tmp;
long count = 0;
while((tmp = bis.read()) != -1){
char c = Character.toLowerCase((char)tmp);
int pos = c - 'a';
if((pos >= 0) && (pos <= 25)){
count++;
}
}
bis.close();
System.out.println(count + " characters");
}
}
比較結果
java apiドキュメントの一部を読み込んで比較。
バッファリングなし。 ![]() バッファリングあり。 ![]() バッファリングを行った方が格別に速い。 Advertisement |
ショートカット・634・このカテゴリのトップページに戻る ・634labs UIコレクションギャラリー サイト検索Y!ログール |