質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
ファイル

ファイルとは、文字列に基づいた名前又はパスからアクセスすることができる、任意の情報のブロック又は情報を格納するためのリソースです。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Q&A

解決済

2回答

929閲覧

Read a file and Output the files

退会済みユーザー

退会済みユーザー

総合スコア0

ファイル

ファイルとは、文字列に基づいた名前又はパスからアクセスすることができる、任意の情報のブロック又は情報を格納するためのリソースです。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

0グッド

0クリップ

投稿2020/05/20 07:20

編集2020/05/21 08:01

前提・実現したいこと

お知恵をお貸しいただけると幸いです。
<実現>
・ファイルに書き込みとコンソールに出力は任意のメソッドを作成して処理を行いたい。
・一行ずつ読み込んでファイルに書き込みとコンソールに出力をさせたい
・extractメソッドにあるclose()が必要なところにfinally句で必ず実行させるようにしたい。 
<前提>
1:「app.log」というファイルを読み込んで、「ERROR」「FATAL」行の先頭に「★」印を印字したファイル「app_error.log」を作成
2:「app.log」というファイルを読み込んで、「2019年1月11日」の記録を抽出した「app_20190111.log」を作成
3: [ERROR」「FATAL 」行の先頭に「★」印を印字して、引数で指定されたファイルに出力するメソッド「markErrorLine」を作成
4: 引数で渡された日付(Calendar-Class)に該当する行をファイルに出力する メソッド「extractDateLog」を作成
5: 結果として、以下のように記載の内容を表示したい。

ExampleOfOutput:
1.実行処理
ログファイルの解析処理を開始します
ログファイルの解析処理を終了しました
2. app_error.log
★2019/01/12 13:30:23.530 ERROR (DBLogic.java getConnection) - DBコネクション取得
★2019/01/12 13:30:23.530 FATAL (AbstractLogic.java execute) - システム例外 発生
2019/01/13 13:30:10.861 DEBUG (DBLogic.java getConnection) - DBコネクション取得
2019/01/13 13:30:10.923 DEBUG (DBLogic.java closeConnection) - DBコネクションクローズ
3.app_20190111.log
2019/01/11 13:30:10.861 DEBUG (DBLogic.java getConnection) - DBコネクション取得
2019/01/11 13:30:10.923 DEBUG (DBLogic.java closeConnection) - DBコネクションクローズ

該当のソースコード

Java

1import java.io.BufferedReader; 2import java.io.BufferedWriter; 3import java.io.File; 4import java.io.FileNotFoundException; 5import java.io.FileReader; 6import java.io.FileWriter; 7import java.io.IOException; 8import java.io.PrintWriter; 9import java.text.SimpleDateFormat; 10import java.util.ArrayList; 11import java.util.Calendar; 12import java.util.Date; 13import java.util.regex.Matcher; 14import java.util.regex.Pattern; 15 16/** 17 *ログファイル「app.log」を読み込んで、下記ファイルを作成するプログラム 18 *「FATAL」「ERROR」行の先頭に「★」印を印字したファイル「app_error.log」 19 *「2019年1月11日」の記録を抜き出したファイル「app_20190111.log」 20 */ 21public class Exercise10 { 22 /** 23 * main 24 * execute method を呼び出す 25 * @param 実行時引数 26 * 27 * 28 * */ 29 public static void main(String[] args) { 30 31 Exercise10 ex10 = new Exercise10(); 32 try { 33 ex10.execute(); 34 } catch (IOException e) { 35 System.out.println("入出力例外が発生しました"); 36 System.exit(1); 37 38 } 39 } 40 41 /** 42 *Execute method 43 *markErrorLine method and extractDateLog method を呼び出し、 44 * @throws IOException 45 */ 46 public void execute() throws IOException { 47 48 System.out.println("1. 実行処理"); 49 50 System.out.println("ログファイルの解析処理を開始します"); 51 52 ArrayList<String> textLines = new ArrayList<String>(); 53 54 55 File file = new File("..\app.log"); 56 try( FileReader fr = new FileReader(file); 57 BufferedReader br = new BufferedReader(fr);){ 58 59 60 61 62 63 String line; 64 while ((line = br.readLine()) != null) { 65 66 textLines.add(line); 67 } 68 69 70 System.out.println("ログファイルの解析処理を終了しました"); 71 }catch(FileNotFoundException f) { 72 System.out.println("ファイルが見つかりません。[リンク内容](https://eng-entrance.com/java-finally)"); 73 System.exit(1); 74 } catch (IOException e) { 75 System.out.println("入出力例外が発生しました"); 76 System.exit(1); 77 } 78 79 //「app_error.log」ファイルを作成 80 File newErrorfile = new File("..\app_error.log"); 81 newErrorfile.createNewFile(); 82 83 84 System.out.println("2. app_error.log"); 85 // Exercise10 ex10 = new Exercise10(); 86 87 markErrorLine(newErrorfile, textLines); 88 89 Calendar cal = Calendar.getInstance(); 90 cal.set(2019, 00, 11); 91 92 System.out.println("3. app_20190111.log"); 93 extractDateLog(cal, textLines); 94 95 } 96 97 /** 98 *markErrorLine method 99 * @param textLines 100 * @param newErrorfile 101 * @throws IOException 102 */ 103 104 public void markErrorLine(File newErrorfile, ArrayList<String> textLines) 105 throws IOException { 106 107 108 //ファイル・コンソールに出力 109 try(PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(newErrorfile)));){ 110 for (String l : textLines) { 111 pw.println(l.replaceFirst("^(.*)(FATAL|ERROR)(.*)$", "★$0")); 112 System.out.println(l.replaceFirst("^(.*)(FATAL|ERROR)(.*)$", "★$0")); 113 } 114 //pw.close(); 115 } 116 } 117 118 119 120 /** 121 *extractDateLog method 122 * 123 * @param cal 124 * @param textLines 125 * @throws IOException 126 */ 127 public static void extractDateLog(Calendar cal, ArrayList<String> textLines) throws IOException { 128 Date date = cal.getTime(); 129 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); 130 String strDate = dateFormat.format(date); 131 132 SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); 133 134 //「app_20190111.log」ファイルを作成 135 String s = "..\app_"+ df.format(date) + ".log"; 136 137 138 File newDatefile = new File(s); 139 newDatefile.createNewFile(); 140 141 // ファイル出力 142 PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(newDatefile))); 143 for (String l : textLines) { 144 Pattern p = Pattern.compile(strDate); 145 Matcher m = p.matcher(l); 146 if (m.find()) { 147 pw.println(l); 148 System.out.println(l); 149 } 150 } 151 pw.close(); 152 153 154 } 155}

試したこと

何故かERROR or FATAL 以外のやつはコンソールに出力されるが、ファイルには一行しか書き込まれていない。
ERRORやFATALに合致したログを★を付け加えて編集させて出力とファイルに書き込みしたいのに、これは出力も書き込みもされていませんでした。

java

1import java.io.BufferedReader; 2import java.io.BufferedWriter; 3import java.io.File; 4import java.io.FileNotFoundException; 5import java.io.FileReader; 6import java.io.FileWriter; 7import java.io.IOException; 8import java.io.PrintWriter; 9import java.text.SimpleDateFormat; 10import java.util.Calendar; 11import java.util.Date; 12import java.util.regex.Matcher; 13import java.util.regex.Pattern; 14 15/** 16 *ログファイル「app.log」を読み込んで、下記ファイルを作成するプログラム 17 *「FATAL」「ERROR」行の先頭に「★」印を印字したファイル「app_error.log」 18 *「2019年1月11日」の記録を抜き出したファイル「app_20190111.log」 19 */ 20public class Test10 { 21 /** 22 * main 23 * execute method を呼び出す 24 * @param 実行時引数 25 * 26 * 27 * */ 28 public static void main(String[] args) { 29 30 Test10 ex10 = new Test10(); 31 try { 32 ex10.execute(); 33 } catch (IOException e) { 34 System.out.println("入出力例外が発生しました"); 35 System.exit(1); 36 37 } 38 } 39 40 /** 41 *Execute method 42 *markErrorLine method and extractDateLog method を呼び出し、 43 * @throws IOException 44 */ 45 public void execute() throws IOException { 46 47 System.out.println("1. 実行処理"); 48 49 System.out.println("ログファイルの解析処理を開始します"); 50 System.out.println("ログファイルの解析処理を終了しました"); 51 //ArrayList<String> textLines = new ArrayList<String>(); 52 53 54 File file = new File("..\app.log"); 55 try( FileReader fr = new FileReader(file); 56 BufferedReader br = new BufferedReader(fr);){ 57 //「app_error.log」ファイルを作成 58 File newErrorfile = new File("..\app_error.log"); 59 newErrorfile.createNewFile(); 60 61 Calendar cal = Calendar.getInstance(); 62 cal.set(2019, 00, 11); 63 64 65 66 String line; 67 while ((line = br.readLine()) != null) { 68 markErrorLine(newErrorfile, line); 69 extractDateLog(cal, line); 70 71 //textLines.add(line); 72 } 73 74 75 76 }catch(FileNotFoundException f) { 77 System.out.println("There is no files to be read"); 78 System.exit(1); 79 } catch (IOException e) { 80 System.out.println("入出力例外が発生しました"); 81 System.exit(1); 82 } 83 84 85 86 87 System.out.println("2. app_error.log"); 88 // Exercise10 ex10 = new Exercise10(); 89 90 //markErrorLine(newErrorfile, textLines); 91 92 93 System.out.println("3. app_20190111.log"); 94 95 96 } 97 98 /** 99 *markErrorLine method 100 * @param line 101 * @param newErrorfile 102 * @throws IOException 103 */ 104 105 public void markErrorLine(File newErrorfile, String line) 106 throws IOException { 107 if(line.isEmpty()){ 108 String str2 = line.replaceFirst("^(.*)(FATAL|ERROR)(.*)$", "★$0"); 109 Fileoutput(newErrorfile, str2); 110 111 //ファイル・コンソールに出力 112 //try(PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(newErrorfile)));){ 113 //for (String l : textLines) { 114 //pw.println(l.replaceFirst("^(.*)(FATAL|ERROR)(.*)$", "★$0")); 115 //System.out.println(l.replaceFirst("^(.*)(FATAL|ERROR)(.*)$", "★$0")); 116 //} 117 //pw.close(); 118 } 119 } 120 121 //ファイル・コンソールに出力用にメソッドを作成 122 public void Fileoutput(File s , String str2 ){ 123 PrintWriter pw = null; 124 try { 125 pw = new PrintWriter(new BufferedWriter(new FileWriter(s))); 126 pw.println(str2); 127 System.out.println(str2); 128 } catch (IOException e) { 129 130 e.printStackTrace(); 131 }finally {pw.close(); 132 133 } 134 135} 136 137 /** 138 *extractDateLog method 139 * 140 * @param cal 141 * @param line 142 * @throws IOException 143 */ 144 public void extractDateLog(Calendar cal, String line) throws IOException { 145 Date date = cal.getTime(); 146 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); 147 String strDate = dateFormat.format(date); 148 SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); 149 150 //「app_20190111.log」ファイルを作成 151 String s = "..\app_"+ df.format(date) + ".log"; 152 153 File newDatefile = new File(s); 154 newDatefile.createNewFile(); 155 Pattern p = Pattern.compile(strDate); 156 Matcher m = p.matcher(line); 157 if (m.find()) { 158 Fileoutput( newDatefile , line); 159 } 160 161 162 } 163}

Finally句

補足情報(FW/ツールのバージョンなど)

java_1.8
eclipse_version_14
###追記1
変数に結果を代入してファイル・コンソールに出力させた。

try(PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(newErrorfile)));){ for (String l : textLines) { String s1 = l.replaceFirst("^(.*)(FATAL|ERROR)(.*)$", "★$0"); pw.println(s1); System.out.println(s1); } //pw.close(); } }

###追記2
extractDateLog メソッドを実行した後に"3.app_201911.log"を出力しているため、コンソール出力・ファイル書き込み後に出力されていることに気がつきました。
ただ、while文のなかでextractDateLogメソッドを実行する直前に記述しても一行ずつ"3.app_201911.log"が出力される気がします。
どう修正すればよいかどなたかご教示願います。

Java

1String line; 2 while ((line = br.readLine()) != null) { 3 markErrorLine(newErrorfile, line); 4 extractDateLog(cal, line); 5 6 7 } 8System.out.println("3. app_20190111.log");

出力結果;

2019/01/16 13:30:23.467 DEBUG (WriteOperationLogLogic.java insert) - ログ証跡出力 終了 2019/01/16 13:30:23.530 DEBUG (DBLogic.java commit) - トランザクションコミット 3. app_20190111.log

###追記3
mark method を用いたら解決しました。

br.mark((int)file.length()); String line; while ((line = br.readLine()) != null) { markErrorLine(newErrorfile, line); } br.reset(); System.out.println("3. app_20190111.log"); String line1; while ((line1 = br.readLine()) != null) { extractDateLog(cal, line1); }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

ベストアンサー

全部Listに読むclass Exercise10から、1行ずつ処理をするclass Test10に書き換えているのですね。

とりあえず下記2点で意図通りの動作でしょうか。

Java

1public void markErrorLine(File newErrorfile, String line) { 2 if (!line.isEmpty()) {

条件が逆です。

Java

1public void Fileoutput(File s, String str2) { 2 try (PrintWriter pw = new PrintWriter(new FileWriter(s, true))) {

trueがないと常に新しい1行で上書きされてしまいます。

投稿2020/05/20 15:30

TN8001

総合スコア9296

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2020/05/21 01:38

exercise10 class では、おっしゃる通り全て読み込んでからリストに格納しておりましたが、読み込むlogは実務では膨大なため Out of memoryが発生すると考え,Test10 classで一行ずつ読み込んで処理を行う方法に切り替えました。 ご教示頂いたコードに変更しましたらコンソールに出力・ファイル書き込み出来ました。 ありがとうございました。 上書きされていることに気がつきませんでした。
guest

0

追記2に関して
markメソッドを用いたらできました。

Java

1 2 br.mark((int)file.length()); 3 String line; 4 while ((line = br.readLine()) != null) { 5 markErrorLine(newErrorfile, line); 6 7 8 } 9 br.reset(); 10 System.out.println("3. app_20190111.log"); 11 12 String line1; 13 while ((line1 = br.readLine()) != null) { 14 15 extractDateLog(cal, line1); 16 17 18 } 19

投稿2020/05/21 07:56

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問