{Java}ファイル操作

 

https://camp.trainocate.co.jp/magazine/java-file/
https://www.tabnine.com/code/java/methods/java.io.OutputStreamWriter/append
https://hikaen2.hatenablog.com/entry/20151026/1445873297


想定シナリオ:
エクセルからデータを取得し、すべての列をスペースで連結してテキストファイルに書き込む

 

 

import java.io.*;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.*;


public class a {
  public static void main(String[] args) throws EncryptedDocumentException, IOException{

    Row row;
    Cell cell_0;
    Cell cell_1;
    Cell cell_2;
    int i;

    // 1. テスト用ファイル作成

    // 出力用のストリームを用意
    FileOutputStream ofs1 = new FileOutputStream("a.xlsx");
    // Excelファイルを作成
    Workbook  wb1 = new XSSFWorkbook(); 
    // シートを作成
    Sheet ws1 = wb1.createSheet("Sheet1");

    for(i = 0; i<= 10; i++){
      // 行を作成
      row = ws1.createRow(i);

      // セルを作成
      cell_0 = row.createCell(0);
      cell_1 = row.createCell(1);
      cell_2 = row.createCell(2);

      // セルに値を設定
      if(i == 0){
        cell_0.setCellValue("col1");
        cell_1.setCellValue("col2");
        cell_2.setCellValue("col3");
      } else  {
        cell_0.setCellValue("A"+i);
        cell_1.setCellValue("あ"+i);
        cell_2.setCellValue(String.valueOf(i) );
      }
    }

    // ファイルへ出力
    wb1.write(ofs1);
    wb1.close();


    // 2. ファイル出力
    // シートの内容を取得
    // 1行目が空になったら終了

    FileOutputStream stream = new FileOutputStream("./b.txt");
    OutputStreamWriter writer = new OutputStreamWriter(stream);
    
    // Excelファイルへアクセス
    Workbook wb2 = WorkbookFactory.create(new File("a.xlsx") );
    // シートを取得
    Sheet ws2 = wb2.getSheet("Sheet1");

    i = 0;
    while ( true ){
      row = ws1.getRow(i+1);

      if( row == null ) {
        break;
      }

    // セルの値を取得
    cell_0 = row.getCell(0);
    cell_1 = row.getCell(1);
    cell_2 = row.getCell(2);

    writer.append(cell_0.getStringCellValue()+" "+cell_1.getStringCellValue()+" "+cell_2.getStringCellValue()+"\r\n" );

    i++;
    }

    wb2.close();

    writer.close();
    stream.close();


     // 3. 出力ファイル確認
    FileReader fr = new FileReader("./b.txt");
    BufferedReader reader = new BufferedReader(fr);

    // 1行目を読み込む
    String line;
    while ((line = reader.readLine() ) != null) {
      System.out.println(line);
    }

    reader.close();
    fr.close();
    
  }
}

 

 


javac -classpath .;log4j-core-2.20.0.jar;poi-bin-5.2.3/*;poi-bin-5.2.3/lib/*;poi-bin-5.2.3/ooxml-lib/* a.java
java  -classpath .;log4j-core-2.20.0.jar;poi-bin-5.2.3/*;poi-bin-5.2.3/lib/*;poi-bin-5.2.3/ooxml-lib/* a