【Java】ファイルの読み書き ~ 新API版 ~

はじめに

https://blogs.yahoo.co.jp/dk521123/32132680.html
で、ファイルの読み書きを行ったが、
Java7以上でもっと簡単に書けるようになったのでメモ

サンプル

 * 例として、MySQLダンプのテンプレートファイルから、
   複数のダンプファイルを生成するプログラムを作成する

FileUtil.java

import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;

public class FileUtil {
  private static final String DEFAULT_CHARSET = "UTF-8";
  private static final String DEFAULT_NEW_LINE_SEPARATOR = System.getProperty("line.separator");

  public static String readAll(Path path) throws IOException {
    return FileUtil.readAll(path, DEFAULT_CHARSET, DEFAULT_NEW_LINE_SEPARATOR);
  }

  public static String readAll(Path path, String charset, String newLineSeparator) throws IOException {
    return Files.lines(path, Charset.forName(charset)).collect(Collectors.joining(newLineSeparator));
  }

  public static void save(String outoutFile, String content) throws IOException {
    // 追記する場合
    // try (FileWriter fileWriter = new FileWriter(outoutFile, true);) {
    try (FileWriter fileWriter = new FileWriter(outoutFile);) {
      fileWriter.write(content);
    }
  }
}

Main.java

使用者側のサンプル
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;

public class Main {
  private static final String TEMPLATE_FILE = "./etc/TemplateExportDb.sql";
  private static final String FORMAT_OF_EXPORT_FILE = "./etc/ExportDb{0,number,0000}.sql";
  private static final int MAX_DATA_NUMBER = 3;
  
  public static void main(String[] args) {
    System.out.println("Start...");
    
    try {
      Path path = Paths.get(TEMPLATE_FILE);
      String conetnt = FileUtil.readAll(path);
      for (int i = 0; i < MAX_DATA_NUMBER; i++) {
        String targetContent = conetnt;
        
        // ここで、ファイル内容を修正
        
        String targetDbName = MessageFormat.format("sampledb{0,number,0000}", i);
        targetContent = targetContent.replaceAll("sampledbXXXX", targetDbName);
        String targetDataId = MessageFormat.format("''A{0,number,0000}''", i);
        targetContent = targetContent.replaceAll("'AXXXX'", targetDataId);
        
        String outoutFile = MessageFormat.format(FORMAT_OF_EXPORT_FILE, i);
        FileUtil.save(outoutFile, targetContent);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    
    System.out.println("Done!");
  }
}

TemplateExportDb.sql

入力データ(MySQLダンプファイル)
-- sampledbXXXX のデータベース構造をダンプしています
CREATE DATABASE IF NOT EXISTS `sampledbXXXX` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `sampledbXXXX`;

--  テーブル sampledbXXXX.customer の構造をダンプしています
CREATE TABLE IF NOT EXISTS `customer` (
  `id` varchar(5) NOT NULL,
  `first_name` varchar(50) DEFAULT NULL,
  `family_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='顧客';

-- テーブル sampledbXXXX.customer: ~6 rows (approximately) のデータをダンプしています
/*!40000 ALTER TABLE `customer` DISABLE KEYS */;
REPLACE INTO `customer` (`id`, `first_name`, `family_name`) VALUES
	('AXXXX', 'Mike', 'Abel');
/*!40000 ALTER TABLE `customer` ENABLE KEYS */;

出力結果

ExportDb0000.sql (~ ExportDb0002.sql)
-- sampledb0000 のデータベース構造をダンプしています
CREATE DATABASE IF NOT EXISTS `sampledb0000` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `sampledb0000`;

--  テーブル sampledb0000.customer の構造をダンプしています
CREATE TABLE IF NOT EXISTS `customer` (
  `id` varchar(5) NOT NULL,
  `first_name` varchar(50) DEFAULT NULL,
  `family_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='顧客';

-- テーブル sampledb0000.customer: ~6 rows (approximately) のデータをダンプしています
/*!40000 ALTER TABLE `customer` DISABLE KEYS */;
REPLACE INTO `customer` (`id`, `first_name`, `family_name`) VALUES
	('A0000', 'Mike', 'Abel');
/*!40000 ALTER TABLE `customer` ENABLE KEYS */;


関連記事

Java】ファイルの読み書き

https://blogs.yahoo.co.jp/dk521123/32132680.html

MySQL】 データのエクスポート / バックアップを行うには... ~ mysqldump ~

https://blogs.yahoo.co.jp/dk521123/36680883.html

シェルで、複数の mysqldumpファイル を実行する

https://blogs.yahoo.co.jp/dk521123/36920590.html