テキストファイルを分割

テキストファイルを任意の行数ごとに分割し、別ファイルに保存します。

import javax.swing.*;
import java.io.*;
import javax.swing.filechooser.*;

public class TextDevider {

	/**
	 * 1ファイルあたりの行数
	 */
	private final static int MAX_LINE = 100;

	/**
	 * 分割するファイル
	 */
	private File target = null;

	public static void main(String[] args) {
		JFileChooser chooser = new JFileChooser();
		chooser.setFileFilter(new FileFilter() {
			public boolean accept(File file) {
				return file.getName().endsWith(".txt");
			}

			public String getDescription() {
				return "テキストファイル";
			}
		});

		if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
			TextDevider devider = new TextDevider(chooser.getSelectedFile());

			try {
				int num = devider.execDevide();
				System.out.println(num + "ファイルに分割");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("キャンセル");
		}
	}

	/**
	 * TextDeviderクラスのコンストラクタです。分割するテキストファイルを引数として渡します。
	 * 
	 * @param file 分割するテキストファイル
	 */
	public TextDevider(final File file) {
		this.target = file;
	}

	/**
	 * テキストファイルの分割を実行します。分割したファイルは分割するファイルと同じディレクトリに保存されます。
	 * 
	 * @throws IOException
	 * @return 分割したファイル数
	 */
	public int execDevide() throws IOException {
		BufferedReader reader = null;
		PrintWriter writer = null;
		boolean isFinished = false;
		int fileCount = 0;

		try {
			reader = new BufferedReader(new FileReader(this.target));
			fileCount = 0;
			
			while (!isFinished) {
				File saveFile = new File(getSaveFilePath(fileCount));
				writer = new PrintWriter(new FileWriter(saveFile));
				String line = null;
				fileCount++;

				for (int lineCount = 0; lineCount < MAX_LINE
						&& (line = reader.readLine()) != null; lineCount++) {
					writer.println(line);
				}

				isFinished = (line == null);
				writer.close();
				writer = null;
			}
		} finally {
			if (writer != null) {
				writer.close();
			}
			// writer.closeは例外を投げないので、reader.closeは確実に実行される
			if (reader != null) {
				reader.close();
			}
		}
		return fileCount;
	}

	/**
	 * 分割したファイルのパスを決定します。
	 * 
	 * @param count
	 *            分割したファイルの順番を表す整数値
	 * @return 分割したファイルのパス
	 */
	private String getSaveFilePath(final int count) {
		return this.target.getPath() + "_" + count;
	}
}