Programming with Java, part 9

記事
IT・テクノロジー

1.About FileWriter class

This time I will talk about file output. There is a class called
FileWriter in the java.io package, so let's first see how to
use this class.

----------------------- WriteTest.java -------------------------------------
import java.io.*;

public class WriteTest {
    public static void main(String[] args) throws Exception {
        FileWriter fw = null;
        try {
            File file = new File("c:¥¥test¥¥test.txt");
            fw = new FileWriter(file);
            fw.write("Hello world");

        } catch(FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        } finally {
             // Close the file.
            if(fw != null) fw.close();
        }
    }        
}
---------------------------------------------------------------------------------

Since FileWriter class is used, describe "import java.io. *;".
Creating an object of File class with new is the same as
when inputting a file. Use this object to objectify a
FileWriter class. FileWriter has a write method, and if you
pass a string to its method, a string will be written to the file.
Finally close the file and finish. This time as well, prepare
with try-catch in case of an exception during file operation.
Also, when writing a new line with the FileWriter class,

             fw.write ("Hello world¥r¥n");

In this way, write "¥r¥n" that represents a new line at
the end of the character string. When running the program
on Windows, it is "¥r¥n", and the newline code differs
depending on the OS, so be careful.


2.About BufferedWriter class

The BufferedWriter class is provided for efficient writing
to files. Let's see how to use this class.

----------------------- WriteTest2.java ------------------------------------
import java.io.*;

public class WriteTest2 {
    public static void main(String[] args) throws Exception {
        BufferedWriter bw = null;
        try {
            File file = new File("c:¥¥test¥¥test.txt");
            FileWriter fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.write("Hello world");
            bw.newLine();

        } catch(FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        } finally {
             // Close the file.
            if(bw != null) bw.close();
        }
    }        
}
---------------------------------------------------------------------------------

Use the FileWriter object to objectify a BufferedWriter
class. Output the strings to the file with the write method.
The difference from FileWriter is the part where a new
line is written. In case of BufferedWriter, there is no need
to write a newline code with the write method. You should
use the newLine method.


3.Measurement of processing speed

I was wondering how efficient BufferedWriter is, so
I measured the processing speed this time as well.
The following is the program when measured.

----------------------- WriteTest.java -------------------------------------
import java.io.*;
public class WriteTest {
 public static void main(String args[]) throws Exception{
  FileWriter fw = null;
  try {
   File file = new File("test.txt");
   fw = new FileWriter(file);
   // Measurement starts.
   long startTime = System.currentTimeMillis();
   for(int i=0; i<10000; i++) {
    fw.write("1234567890\r\n");
   }
   // Measurement ends.
   long endTime = System.currentTimeMillis();
   System.out.println("Time(ms):" + (endTime - startTime));
  } catch(FileNotFoundException e) {
   System.out.println(e);
  } catch(IOException e) {
   System.out.println(e);
  } finally {
   // Close the file.
   if(fw != null) fw.close();
  }
 }
}
---------------------------------------------------------------------------------

----------------------- WriteTest2.java ------------------------------------
import java.io.*;
public class WriteTest2 {
 public static void main(String args[]) throws Exception{
  BufferedWriter bw = null;
  try {
   File file = new File("test.txt");
   FileWriter fw = new FileWriter(file);
   bw = new BufferedWriter(fw);
   // Measurement starts.
   long startTime = System.currentTimeMillis();
   for(int i=0; i<10000; i++) {
    bw.write("1234567890");
    bw.newLine();
   }
   // Measurement ends.
   long endTime = System.currentTimeMillis();
   System.out.println("Time(ms):" + (endTime - startTime));
  } catch(FileNotFoundException e) {
   System.out.println(e);
  } catch(IOException e) {
   System.out.println(e);
  } finally {
   // Close the file.
   if(bw != null) bw.close();
  }
 }
}
---------------------------------------------------------------------------------

■ Contents to be output to a file
10,000 lines of half-width "1234567890"
(The file size is 120KB.)

■ Measurement result
(Average of 5 measurements, unit is millisecond)
FileWriter:19ms
BufferedWriter:3ms


BufferedWriter was not less than 6 times faster.
Several times out of 5, BufferedWriter was processed
in 0ms (less than 1ms). It turned out to be quite faster
than FileWriter.


[Japanese]

1.FileWriterクラスについて

今回はファイル出力のお話です。java.ioパッケージにFileWriterというクラスがありますので、まずはこのクラスを使った方法を見ていきましょう。

----------------------- WriteTest.java -------------------------------------
import java.io.*;

public class WriteTest {
    public static void main(String[] args) throws Exception {
        FileWriter fw = null;
        try {
            File file = new File("c:¥¥test¥¥test.txt");
            fw = new FileWriter(file);
            fw.write("Hello world");

        } catch(FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        } finally {
             // Close the file.
            if(fw != null) fw.close();
        }
    }        
}
---------------------------------------------------------------------------------

FileWriterクラスを利用するので、「import java.io.*;」を記述します。
newでFileクラスのオブジェクトを作るのは、ファイル入力の時と同じです。このオブジェクトを利用して、FileWriterクラスをnewします。
FileWriterにはwriteメソッドが用意されており、String型の文字列を渡すとファイルに書き込んでくれます。最後にファイルを閉じて終了です。今回もファイル操作中の例外に備えて、try - catch処理を記述しています。
また、FileWriterクラスで改行を書き込む場合、
            fw.write("Hello world¥r¥n");
このように文字列の末尾に改行を表す「¥r¥n」を記述します。
プログラムをWindowsで動かす場合は「¥r¥n」で、OSによって改行コードが異なりますので、注意が必要です。



2.BufferedWriterクラスについて

ファイルに効率良く書き込むために、BufferedWriterクラスが提供されています。このクラスの使用方法を見ていきましょう。

----------------------- WriteTest2.java ------------------------------------
import java.io.*;

public class WriteTest2 {
    public static void main(String[] args) throws Exception {
        BufferedWriter bw = null;
        try {
            File file = new File("c:¥¥test¥¥test.txt");
            FileWriter fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.write("Hello world");
            bw.newLine();

        } catch(FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        } finally {
             // Close the file.
            if(bw != null) bw.close();
        }
    }        
}
---------------------------------------------------------------------------------

FileWriterのオブジェクトを利用して、BufferedWriterクラスをnewします。ファイルへの書き込みはwriteメソッドで行います。FileWriterと異なるのは、改行を書き込む部分です。BufferedWriterでは、writeメソッドで改行コードを書き込む必要はありません。newLineメソッドを呼び出せば良いのです。


3.処理速度の計測

BufferedWriterがどのくらい効率が良いのか気になったので、今回も処理速度を計測してみました。下記が計測したときのプログラムです。

----------------------- WriteTest.java -------------------------------------
import java.io.*;
public class WriteTest {
 public static void main(String args[]) throws Exception{
  FileWriter fw = null;
  try {
   File file = new File("test.txt");
   fw = new FileWriter(file);
   // Measurement starts.
   long startTime = System.currentTimeMillis();
   for(int i=0; i<10000; i++) {
    fw.write("1234567890\r\n");
   }
   // Measurement ends.
   long endTime = System.currentTimeMillis();
   System.out.println("Time(ms):" + (endTime - startTime));
  } catch(FileNotFoundException e) {
   System.out.println(e);
  } catch(IOException e) {
   System.out.println(e);
  } finally {
   // Close the file.
   if(fw != null) fw.close();
  }
 }
}
---------------------------------------------------------------------------------

----------------------- WriteTest2.java ------------------------------------
import java.io.*;
public class WriteTest2 {
 public static void main(String args[]) throws Exception{
  BufferedWriter bw = null;
  try {
   File file = new File("test.txt");
   FileWriter fw = new FileWriter(file);
   bw = new BufferedWriter(fw);
   // Measurement starts.
   long startTime = System.currentTimeMillis();
   for(int i=0; i<10000; i++) {
    bw.write("1234567890");
    bw.newLine();
   }
   // Measurement ends.
   long endTime = System.currentTimeMillis();
   System.out.println("Time(ms):" + (endTime - startTime));
  } catch(FileNotFoundException e) {
   System.out.println(e);
  } catch(IOException e) {
   System.out.println(e);
  } finally {
   // Close the file.
   if(bw != null) bw.close();
  }
 }
}
---------------------------------------------------------------------------------

■ ファイルに出力する内容
半角の「1234567890」を1万行(ファイルサイズは120KB)

■ 計測結果(5回の計測の平均、単位はミリ秒)
FileWriter:19ms
BufferedWriter:3ms


BufferedWriterの方が6倍以上速かったです。5回計測した中で、BufferedWriterは0ms(1ms未満)で処理されることが何度かありましたので、FileWriterよりも相当速いことが分かりました。
サービス数40万件のスキルマーケット、あなたにぴったりのサービスを探す