トッカンソフトウェア

テキストファイル

今回はテキストファイルの読み書きをやります。Jsp、サーブレットというよりJavaの内容ですが、Jsp、サーブレットでも
使う機会が多いと思われるので、別ジャンルかもしれませんがやります。


テキストファイルの読み書き


package test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileTest {

	public static void main(String[] args) {

		String filePath = "C:\\work\\hp\\test.txt";

		// ファイル読み込みテスト
		List<String> ret = read(filePath);

		ret.add("ファイル書き込み");

		// ファイル書き込みテスト
		write(filePath, ret);

		// ファイル追記
		append(filePath, "ファイル追記");
	}

	/**
	 * テキストファイル読み込み
	 * 
	 * @param path ファイルパス
	 * @return ファイルデータ
	 */
	public static List<String> read(String path) {

		ArrayList<String> ret = new ArrayList<>();

		try (BufferedReader br = new BufferedReader(new FileReader(path))) {

			String line;

			while ((line = br.readLine()) != null) {

				ret.add(line);
			}
		} catch (IOException e) {

			e.printStackTrace();
		}
		return ret;
	}

	/**
	 * ファイル書き込み
	 * 
	 * @param path ファイルパス
	 * @param ary  ファイルデータ
	 */
	public static void write(String path, List<String> ary) {

		StringBuilder stb = new StringBuilder();

		for (String str : ary) {

			stb.append(str);
			stb.append(System.lineSeparator());
		}

		try (FileWriter filewriter = new FileWriter(path, false)) {

			filewriter.write(stb.toString());

		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	/**
	 * ファイル追記
	 * 
	 * @param path ファイルパス
	 * @param str  追記テキスト
	 */
	public static void append(String path, String str) {

		try (FileWriter filewriter = new FileWriter(path, true)) {

			filewriter.write(str);
			filewriter.write(System.lineSeparator());

		} catch (IOException e) {

			e.printStackTrace();
		}
	}
}

ファイル読み込み

テキストファイルの読み込みはFileReaderクラスで行います。これだけでも読み込めるのですが、これにBufferedReaderをかぶせる
ことで使い勝手がよくなります。
				
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
	
			

ファイルを読み込んだら、クローズ処理を行う必要があるのですが、try-with-resourcesを利用することにより
クローズ処理の記述を省略できます。


ファイル書き込み

テキストファイルの書き込みはFileWriterクラスを使用します。
				
try (FileWriter filewriter = new FileWriter(path, false)) {
	
			
これもクローズ処理を行う必要があるのですが、try-with-resourcesよりクローズ処理の記述を省略できます。

ファイル追記

テキストファイルの追記は、FileWriterクラスで第二引数にtrueを指定すると追記されるようになります。
				
try (FileWriter filewriter = new FileWriter(path, true)) {
	
			

改行

改行文字はSystem.lineSeparator()で埋め込めます。"\r\n"でもいけます。
				
System.lineSeparator()


			

テキストファイルの読み書き(UTF8)

上記サンプルを文字コード:UTF8版にすると以下になります。

package test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class FileTest {

	public static void main(String[] args) {

		String filePath = "C:\\work\\hp\\test.txt";

		// ファイル読み込みテスト
		List<String> ret = read(filePath);

		ret.add("ファイル書き込み");

		// ファイル書き込みテスト
		write(filePath, ret);

		// ファイル追記
		append(filePath, "ファイル追記");
	}

	/**
	 * テキストファイル読み込み
	 * 
	 * @param path ファイルパス
	 * @return ファイルデータ
	 */
	public static List<String> read(String path) {

		List<String> ret = new ArrayList<>();

		try (BufferedReader br = new BufferedReader(
				new InputStreamReader(new FileInputStream(new File(path)), "UTF-8"))) {

			String line;

			while ((line = br.readLine()) != null) {

				ret.add(line);
			}
		} catch (IOException e) {

			e.printStackTrace();
		}

		return ret;
	}

	/**
	 * ファイル書き込み
	 * 
	 * @param path ファイルパス
	 * @param ary  ファイルデータ
	 */
	public static void write(String path, List<String> ary) {

		try (PrintWriter printwriter = new PrintWriter(
				new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path), false), "UTF-8")))) {

			for (String str : ary) {

				printwriter.println(str);
			}
		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	/**
	 * ファイル追記
	 * 
	 * @param path ファイルパス
	 * @param str  追記テキスト
	 */
	public static void append(String path, String str) {

		try (PrintWriter printwriter = new PrintWriter(
				new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path), true), "UTF-8")))) {

			printwriter.println(str);

		} catch (IOException e) {

			e.printStackTrace();
		}
	}
}

シフトJISコードの場合、SJISを指定し、日本語EUCコードの場合、EUC-JPを指定する。
				
	try (BufferedReader br = new BufferedReader(
			new InputStreamReader(new FileInputStream(new File(path)), "UTF-8"))) {

	try (BufferedReader br = new BufferedReader(
			new InputStreamReader(new FileInputStream(new File(path)), "SJIS"))) {

	try (BufferedReader br = new BufferedReader(
			new InputStreamReader(new FileInputStream(new File(path)), "EUC-JP"))) {


			

BOMを取り除いてテキストファイル読み込み


	/**
	 * テキストファイル読み込み(BOM除去)
	 * 
	 * @param path ファイルパス
	 * @return ファイルデータ
	 */
	public static List<String> read(String path) {

		List<String> ret = new ArrayList<>();

		try (BufferedReader br = new BufferedReader(
				new InputStreamReader(new FileInputStream(new File(path)), "UTF-8"))) {

			String line;

			while ((line = br.readLine()) != null) {

				if (ret.size() == 0 && line.startsWith("\uFEFF")) {

					ret.add(line.substring(1));
					
				} else {

					ret.add(line);
				}
			}
		} catch (IOException e) {

			e.printStackTrace();
		}

		return ret;
	}

ページのトップへ戻る