Programming with Java, part 7

記事
IT・テクノロジー

About file input

Since it is common to manage data with a DB, it is the
mainstream to acquire or register data in a DB using SQL.
It will be introduced in another time.
In addition, there are also scenes where you perform file
operations from Java, such as receiving a file (CSV file, etc.)
from the outside and importing it into the DB, or outputting
the contents of the DB to a file and providing it to the outside.
This time, I will talk about the file input.

1.png

There are the following two types of file input / output in Java.
・Byte stream
・Character stream
8 bits = 1 byte, and the byte stream inputs / outputs files
byte by byte. The character stream inputs / outputs files
character by character. This time, let's see how to input
with the character stream.


(1)File class

When you use the files, create an object of File class of
the "java.io" package. First, you write "import java.io.*;".
Next, as shown below, make the file path into a character
string and new File class with it to make an object.

    File file = new File("c:¥¥test¥¥sample.txt");

If you want to run the Java program on Windows, specify
the path as above. Please note that the path will not be
recognized correctly if there is only one ¥, such as
"c:¥test¥sample.txt".


(2)FileReader class

After creating a File object, objectify the FileReader class
in the "java.io" package to read the file.

    FileReader fr = new FileReader(file);

Then use the FileReader's read method to read a single
character. Call the read method repeatedly to read the
contents of the file character by character. There are
several read methods with different parameters, but
the read method without parameters returns the read
character as an int type. It returns -1 when the end of
reading the file is reached.

    int iFileData;
    while((iFileData = fr.read()) != -1){
        // Display the character in the file.
        System.out.print((char)iFileData);
    }

Like this, read until -1 is returned. If you cast (convert)
the read character from int type to char type, you can
check it by displaying it on the screen. After reading the
file, close the file with the close method.

    // Close the file.
    fr.close();


■How to be sure to close the file
When you access an external resource(file in this example)
from a Java program, an exception may occur. For example,
in case of that the file does not exist, or the file name is
different from what you expected. Suspending is a fatal
trouble for a program that should not be stopped.
To prevent this, you can use try - catch to prepare for an
exception. In addition, finally can be used to prevent
files from being left open.

----------------------- ReadTest.java -------------------------------------
import java.io.*;

public class ReadTest {
    public static void main(String[] args) throws Exception {
        FileReader fr = null;
        try {
            File file = new File("c:¥¥test¥¥sample.txt");
            fr = new FileReader(file);

            int iFileData;
            while ((iFileData = fr.read()) != -1) {
                // Display the character in the file.
                System.out.print((char)iFileData);
            }
        } catch(FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        } finally {
             // Close the file.
            if(fr != null) fr.close();
        }
    }        
}
---------------------------------------------------------------------------------

The processing in finally is always performed regardless of
whether the processing in try ends normally or an exception
occurs. The file is always closed if an exception occurs
while reading the file.

If the file remains open, you will not be able to add or save
to that file, or you will not be able to delete the file.
If this happens, you will need to take measures such as
killing the process or restarting the server, so be careful
when programming.


Next time, I will continue to talk about file input and
explain the BufferedReader class.


[Japanese]

ファイル入力について

DBでデータを管理するのが一般的ですので、DBに対してSQLを使ってデータ取得や登録を行うのが主流になります。これは別の回で触れる予定です。
その他に、外部からファイル(CSVファイルなど)を受け取ってDBに取り込んだり、DBの内容をファイルに出力して外部へ提供するなど、Javaからファイル操作をする場面もあります。今回は、そのファイル入力についてのお話です。

1.png


Javaでのファイル入出力には、
・バイトストリーム
・文字ストリーム
の2種類があります。8ビット = 1バイトですが、このバイト毎にファイルを入出力するのがバイトストリーム、文字毎が文字ストリームです。
今回は文字ストリームによるファイル入力を見ていきましょう。


(1)Fileクラスについて

これからファイルを扱うので、「java.io」パッケージのFileクラスのオブジェクトを作成します。「import java.io.*;」を書いた後に
    File file = new File("c:¥¥test¥¥sample.txt");
このように、扱うファイルのパスを文字列にしてnewで渡してあげてオブジェクト化します。Javaのプログラムを実行する環境がWindowsの場合は、上記のようにパスを指定します。「c:¥test¥sample.txt」のように、¥が1つずつだとパスが正しく認識されませんので、注意しましょう。


(2)FileReaderクラスについて

Fileオブジェクトを作った後、ファイルを読み込むために「java.io」パッケージのFileReaderクラスをオブジェクト化します。
    FileReader fr = new FileReader(file);
次に、FileReaderのreadメソッドで単一の文字を読み込みます。ファイルの内容を1文字ずつ読み込むため、readメソッドを繰り返し呼び出します。パラメータが異なるreadメソッドがいくつか用意されているのですが、パラメータ無しのreadメソッドは読み込んだ文字をint型で返します。ファイルの読み込みが終わりに達した場合、-1を返します。

    int iFileData;
    while((iFileData = fr.read()) != -1){
        // Display the character in the file.
        System.out.print((char)iFileData);
    }

このように、-1が返されるまで読み込んでください。読み込んだ文字をint型からchar型にキャスト(変換)すれば、画面に表示して確かめることも可能です。ファイルを読み終わった後は、closeメソッドでファイルを閉じます。
    // Close the file.
    fr.close();


■ファイルを必ず閉じるための工夫
Javaのプログラムから外部のリソース(今回の例ではファイル)にアクセスする場合、例外が発生する可能性があります。例えば、ファイルが存在していなかったり、ファイル名が想定していた名前と異なっていたりなどです。もし途中停止してはならないプログラムで、このような例外が起きる度に停止してしまうのは、致命的な問題です。そうならないように、try - catch処理を用いれば例外発生時に備えることができます。それに加えてfinallyを用いると、ファイルの開きっぱなしを防ぐことも可能になります。

----------------------- ReadTest.java -------------------------------------
import java.io.*;

public class ReadTest {
    public static void main(String[] args) throws Exception {
        FileReader fr = null;
        try {
            File file = new File("c:¥¥test¥¥sample.txt");
            fr = new FileReader(file);

            int iFileData;
            while ((iFileData = fr.read()) != -1) {
                // Display the character in the file.
                System.out.print((char)iFileData);
            }
        } catch(FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        } finally {
             // Close the file.
            if(fr != null) fr.close();
        }
    }        
}
---------------------------------------------------------------------------------

finally内の処理は、try内の処理が正常に終了した場合も、例外が発生した場合も、必ず行われます。これによって、ファイル読み込み中に例外が発生しても、ファイルは必ず閉じるようになります。

もしファイルが開いたままになってしまうと、そのファイルに追記や保存ができなくなったり、ファイルが削除できなくなってしまいます。そうなるとプロセスをkillしたり、サーバを再起動するなどの対処が必要になってしまいますので、注意してプログラミングしましょう。


次回もファイル入力についてのお話で、BufferedReaderクラスを解説します。

サービス数40万件のスキルマーケット、あなたにぴったりのサービスを探す