自己投資の一つとしてチャレンジしている Programming の Java の独習状況を Blog で公開しています。今回はファイルの読み込み方法について紹介します。
——————————————————-
▼1. ファイルを読む方法 (Read) の概要
——————————————————-
ファイルは byte の連続なので byte をどのように読むかにより使う method が変わります。

—————————–
1-1, サイズの小さいファイルの read: readAllBytes, readAllLines
1-2, buffered input stream を返しStream I/O の利用した read: newBufferedReader
1-3, unbuffered input stream を返しStream I/O の利用した read:newInputStream
1-4, buffered input stream を返し Channel I/O の利用した read:newByteChannel
—————————–
1-1, サイズの小さいファイルを読む場合、readAllBytes や readAllLines の method を使います。
1-2, buffered input stream を返して (メモリを利用しディスクアクセスなしで) Stream I/O を使い byte を 読む場合、newBufferedReader の method を利用します。
1-3, unbuffered input stream を返して (ディスクにアクセスし) Stream I/O を使い byte を読む場合、newInputStream の method を利用します。
1-4, buffered input stream を返して (メモリを利用しディスクアクセスなしで) Channel I/O を使い Buffer を 読む場合、newByteChannel の method を利用します。
——————————————————-
▼2. ファイルを読む (Read) 方法
——————————————————-
2-1, サイズの小さいファイルを読む場合
readAllBytes でテキストを読み、内容を出力する例
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class readfileallbytesv1 {
private static final Logger log = LoggerFactory.getLogger(readfileallbytesv1.class);
public static void main(String... args){
File file = new File("/home/hoge/tempfile.txt");
String content = "";
try{
content = new String(Files.readAllBytes(Paths.get(file.toURI())));
log.info("{} contains {}",file.getName(),content);
} catch (IOException e){
log.error("Error message: ",e);
}
}
}出力結果は以下。This is a temporary file が実際 tempfile.txt に記載されていた内容。
[main] INFO readfileallbytesv1 - tempfile.txt contains --> This is a temporary file.
2-2, newBufferedReader でファイルを開き、BufferedReader でテキストを読むため unbuffered input stream を返して (ディスクにアクセスし) Stream I/O を使い byte を読む例。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class newbufferedReaderv1 {
private static final Logger log = LoggerFactory.getLogger(newbufferedReaderv1.class);
public static void main(String... args) {
File file = new File("/home/hoge/tempfile.txt");
Path sourceFile = Paths.get(file.toURI());
try (BufferedReader reader = Files.newBufferedReader(sourceFile, StandardCharsets.UTF_8)){
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
log.info("Read with BufferedReader contains --> {}", sb.toString());
} catch (Exception e) {
log.info("Something went wrong! ", e);
}
}
}出力結果は以下。This is a temporary file が実際 tempfile.txt に記載されていた内容。
[main] INFO newbufferedReaderv1 - Read with BufferedReader contains --> This is a temporary file.
2-3, newInputStream でファイルを開き、BufferedReader で byte を読むため、unbuffered input stream を返して (ディスクにアクセスし) Stream I/O を使い byte を読む例。出力の過程で InputStream のインスタンスを BufferedReader のインスタンスでまとめる(ラップする)必要があり、Stream は複数の thread から同時にアクセスできる。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.Reader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class newinputstreamcode {
private static final Logger log = LoggerFactory.getLogger(newinputstreamcode.class);
public static void main(String... args) {
File file = new File("/home/hoge/tempfile.txt");
Path sourceFile = Paths.get(file.toURI());
try (InputStream in = Files.newInputStream(sourceFile)){
InputStreamReader ins = new InputStreamReader(in,StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader (ins);
StringBuilder sb = new StringBuilder();
String line;
while ((line=reader.readLine()) != null) {
sb.append(line);
}
log.info("Read with BufferedReader contains --> {}", sb.toString());
} catch (Exception e) {
log.info("Something went wrong! ", e);
}
}
}出力結果は以下。This is a temporary file が実際 tempfile.txt に記載されていた内容。
[main] INFO newinputstreamcode - Read with BufferedReader contains --> This is a temporary file.
2-4, newByteChannel でファイルを開き、buffered input stream を返して (メモリを利用しディスクアクセスなしで) Channel I/O を使って Buffer を 読む例。
import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.Charset;
public class newByteChannelcode {
private static final Logger log = LoggerFactory.getLogger(newByteChannelcode.class);
public static void main(String... args) throws IOException {
File file = new File("/home/hoge/tempfile.txt");
Path sourceFile = Paths.get(file.toURI());
try (SeekableByteChannel sbc = Files.newByteChannel(sourceFile)){
ByteBuffer buf = ByteBuffer.allocate(100);
String encoding = System.getProperty("file.encoding");
while (sbc.read(buf)>0){
buf.rewind();
log.info("Read with ByteChannel contains --> {}", Charset.forName(encoding).decode(buf));
buf.flip();
}
} catch (IOException e) {
log.info("Something went wrong! ", e);
}
}
}出力結果は以下。This is a temporary file が実際 tempfile.txt に記載されていた内容。
[main] INFO newByteChannelcode - Read with ByteChannel contains --> This is a temporary file.
————————————-
▼3. 参考情報
————————————-
(1) Reading, Writing, and Creating Files https://docs.oracle.com/javase/tutorial/essential/io/file.html
(2) Buffered Streams https://docs.oracle.com/javase/tutorial/essential/io/buffers.html
(3) Module java.base, Package java.nio.file (nio は non-blocking input output の略) https://docs.oracle.com/javase/10/docs/api/java/nio/file/Files.html
以上です。参考になりましたら幸いです。