もやしちょこれーと

りけじょのたまごのいろいろ

LINEのバックアップ(.txt)をCSVに変換するコード

LINEのバックアップ(.txt)をCSVに変換するコードが完成しました!

昨日ごちゃごちゃ言ってたけど、結局javaでゴリゴリ書いちゃいました…(python挫折した

大したブツじゃないし、スマートじゃないけど公開しちゃいます

import java.io.*;

public class talkToCSV {
	public static void main(String args[]) {
		int loopCount = 0;
		String inputFileName = "読み込むファイルのパス";
	    // create file object
	    File inputFile = new File(inputFileName);
	    boolean flag = false;
	    String datetmp = "";
	    String date = "";
	    String day = "";
	    String month = "";
	    String comment = "";
	    String speaker = "";
	    String output = "";
	    try {
	      // read file by utf-8
	      FileInputStream fis = new FileInputStream(inputFile);
	      InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
	      BufferedReader br = new BufferedReader(isr);
	      
	      // output file
	      File outfile = new File("出力ファイルのパス");
	      FileOutputStream fos = new FileOutputStream(outfile);
	      OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
	      PrintWriter pw = new PrintWriter(osw);
	    		  
	      // read from text file
	      String line;
	      String[] data;
	      while ( ( line = br.readLine()) != null ) {
	    	  loopCount++;
	    	  if (loopCount < 3) {	// skip first 3 lines
	    		  continue;
	    	  } else {
		    	  if (line.isEmpty()) {	// date data is in next line
		    		  flag = true;
		    		  continue;
		    	  } else if (flag && line.split("/").length > 2) {
		    		  if (line.charAt(5) == '0')
		    			  month = String.valueOf(line.charAt(6));
		    		  else
		    			  month = String.valueOf(line.charAt(5)) + String.valueOf(line.charAt(6));
		    		  
		    		  if (line.charAt(8) == '0')
		    			  day = String.valueOf(line.charAt(9));
		    		  else
		    			  day = String.valueOf(line.charAt(8)) + String.valueOf(line.charAt(9));
		    		  
		    		  datetmp = month + "/" + day + "/" + line.substring(0, 4) + " ";	// month/day/year
		    		  flag = false;
		    		  continue;
		    	  } else {	// talk data
		    		  flag = false;
		    		  data = line.split("\t");
		    		  if (data.length == 3) {	// this line includes the information of speaker and time
		    			  // write data to file (date, speaker, comment)
		    			  if (!date.isEmpty()) {
			    			  output = (date + "," + speaker + "," + comment + "\r\n");
			    		      pw.print(output);
		    			  }
		    			  // initialize date
		    			  date = ""; speaker = ""; comment = "";
		    			  date = datetmp + data[0];
		    			  speaker = data[1];
		    			  comment = data[2];
		    		  } else {	// this line includes only comment
		    			  comment += (data[0] + "\n");
		    		  }
		    	  }
	    	  }
	      }
	      // for last line
    	  output = (date + "," + speaker + "," + comment + "\r\n");
	      pw.print(output);
	      
	      // close
	      pw.close();
	      br.close();
	    } catch(Exception e) {
	      e.printStackTrace();
	    }
		
	}
}

下準備がやっと出来たので、次はこれで生成したCSVを使ってなんかしようと思います!