一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專(zhuān)注于服務(wù)器技術(shù)及軟件下載分享
分類(lèi)導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術(shù)|正則表達(dá)式|

服務(wù)器之家 - 編程語(yǔ)言 - JAVA教程 - java異步寫(xiě)日志到文件中實(shí)現(xiàn)代碼

java異步寫(xiě)日志到文件中實(shí)現(xiàn)代碼

2020-09-17 14:58nature_fly088 JAVA教程

這篇文章主要介紹了java異步寫(xiě)日志到文件中實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下

java異步寫(xiě)日志文件中詳解

實(shí)現(xiàn)代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package com.tydic.ESUtil;
 
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
 
public class LogWriter {
// 日志的配置文件
  public static final String LOG_CONFIGFILE_NAME = "log.properties";
  // 日志文件名在配置文件中的標(biāo)簽
  public static final String LOGFILE_TAG_NAME = "logfile";
   
  // 默認(rèn)的日志文件的路徑和文件名稱(chēng)
  private final String DEFAULT_LOG_FILE_NAME = "./logtext.log";
  // 該類(lèi)的唯一的實(shí)例
  private static LogWriter logWriter;
  // 文件輸出流
  private PrintWriter writer; 
  // 日志文件名
  private String logFileName; 
  /**
   * 默認(rèn)構(gòu)造函數(shù)
   */
  private LogWriter() throws LogException{
    this.init();
  }
  private LogWriter(String fileName) throws LogException{
    this.logFileName = fileName;
    this.init();
  }
  /**
   * 獲取LogWriter的唯一實(shí)例。
   * @return
   * @throws LogException
   */
  public synchronized static LogWriter getLogWriter()throws LogException{
    if (logWriter == null){
      logWriter = new LogWriter();
    }
    return logWriter;
  }
  public synchronized static LogWriter getLogWriter(String logFileName)throws LogException{
    if (logWriter == null){
      logWriter = new LogWriter(logFileName);
    }
    return logWriter;
  }
 
  /**
   * 往日志文件中寫(xiě)一條日志信息
   * 為了防止多線程同時(shí)操作(寫(xiě))日志文件,造成文件”死鎖”。使用synchronized關(guān)鍵字
   * @param logMsg  日志消息
   */
  public synchronized void log(String logMsg) {
    this.writer.println(new java.util.Date() + ": " + logMsg);
  }
  /**
   * 往日志文件中寫(xiě)一條異常信息
   * 使用synchronized關(guān)鍵字。
   * @param ex  待寫(xiě)入的異常
   */
  public synchronized void log(Exception ex) {
    writer.println(new java.util.Date() + ": ");
    ex.printStackTrace(writer);
  }
 
  /**
   * 初始化LogWriter
   * @throws LogException
   */
  private void init() throws LogException{
    //如果用戶沒(méi)有在參數(shù)中指定日志文件名,則從配置文件中獲取。
    if (this.logFileName == null){
      this.logFileName = this.getLogFileNameFromConfigFile();
      //如果配置文件不存在或者也沒(méi)有指定日志文件名,則用默認(rèn)的日志文件名。
      if (this.logFileName == null){
        this.logFileName = DEFAULT_LOG_FILE_NAME;
      }
    }
    File logFile = new File(this.logFileName);
    try {
      // 其中的FileWriter()中的第二個(gè)參數(shù)的含義是:是否在文件中追加內(nèi)容
      // PrintWriter()中的第二個(gè)參數(shù)的含義是:自動(dòng)將數(shù)據(jù)flush到文件中
      writer = new PrintWriter(new FileWriter(logFile, true), true);
      System.out.println("日志文件的位置:" + logFile.getAbsolutePath());
    } catch (IOException ex) {
      String errmsg = "無(wú)法打開(kāi)日志文件:" + logFile.getAbsolutePath();
      // System.out.println(errmsg);
      throw new LogException(errmsg, ex);
    }
  }
  /**
   * 從配置文件中取日志文件名
   * @return
   */
  private String getLogFileNameFromConfigFile() { 
    try
      Properties pro = new Properties(); 
      //在類(lèi)的當(dāng)前位置,查找屬性配置文件log.properties 
      InputStream fin = getClass().getResourceAsStream(LOG_CONFIGFILE_NAME); 
      if (fin != null){
        pro.load(fin);//載入配置文件
        fin.close(); 
        return pro.getProperty(LOGFILE_TAG_NAME);
      } else {
        System.err.println("無(wú)法打開(kāi)屬性配置文件: log.properties" ); 
      }
    }catch (IOException ex) { 
      System.err.println("無(wú)法打開(kāi)屬性配置文件: log.properties" ); 
    }
    return null;
  }
  //關(guān)閉LogWriter
  public void close() {
    logWriter = null;
    if (writer != null){
      writer.close();
    }
  }
 
  public static void main(String[] args) {
    LogWriter logger = null;
    try {
      String fileName = "d:/temp/logger.log";
      logger = LogWriter.getLogWriter(fileName);
//     logger.log("First log!");
//     logger.log("第二個(gè)日志信息");
//     logger.log("Third log");
//     logger.log("第四個(gè)日志信息");
      String content="tableaA|device_number|13701010";
      StringBuffer sb=new StringBuffer();
      for(int i=0;i<1000000;i++){
        sb.append(content).append(i).append(";\n");
      }
      content=sb.toString();
      long startTime=System.currentTimeMillis();
      logger.log(content);
      long endTime=System.currentTimeMillis();
      System.out.println("總消耗時(shí)間:"+(endTime-startTime));
      logger.close();
//     ReadFromFile.readFileByLines(fileName);
    } catch (LogException e) {
      e.printStackTrace();
    }
  }
}

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.tydic.ESUtil;
 
public class AychWriter extends Thread {
  private String content;
  public AychWriter(String content){
    this.content=content;
  }
  @Override
  public void run(){
    System.out.println("開(kāi)始執(zhí)行run()");
    LogWriter logger = null;
    String fileName = "d:/temp/logger.log";
    long startTime=System.currentTimeMillis();
    try {
      logger = LogWriter.getLogWriter(fileName);
      logger.log(this.content);
    } catch (LogException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
 
    long endTime=System.currentTimeMillis();
    System.out.println("總消耗時(shí)間:"+(endTime-startTime));
  }
}

測(cè)試類(lèi):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.tydic.ESUtil;
 
import java.io.FileWriter;
import java.io.IOException;
 
import org.junit.Test;
 
public class test_test {
  /**
   * 同步向指定文件尾部寫(xiě)入字符串
   */
public void testAppendMethodB(String fileName,String content) throws IOException{
    try {
      //打開(kāi)一個(gè)寫(xiě)文件器,構(gòu)造函數(shù)中的第二個(gè)參數(shù)true表示以追加形式寫(xiě)文件
      FileWriter writer = new FileWriter(fileName, true);
      writer.write(content);
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    }
 
/**
 *調(diào)用上面同步寫(xiě)方法
 */
  @Test
  public void testWriteTOFile() throws IOException{
    String fileName = "d:\\test.txt";
    String content="tableaA|device_number|13701010";
    StringBuffer sb=new StringBuffer();
    for(int i=0;i<100000;i++){
      sb.append(content).append(i).append(";\n");
    }
    content=sb.toString();
    long startTime=System.currentTimeMillis();
    testAppendMethodB(fileName,content);
    long endTime=System.currentTimeMillis();
    System.out.println("總消耗時(shí)間:"+(endTime-startTime));
  }
  /**
   * 異步調(diào)用寫(xiě)方法
   * @throws IOException
   * @throws InterruptedException
   */
  @Test
  public void testAsyncWriteTOFile() throws IOException, InterruptedException{
    String fileName = "d:\\test.txt";
    String content="tableaA|device_number|13701010";
    StringBuffer sb=new StringBuffer();
    for(int i=0;i<100000;i++){
      sb.append(content).append(i).append(";\n");
    }
    content=sb.toString();
    System.out.println("start write...");
    new AychWriter(content).start();
    System.out.println("write over...");
    Thread.sleep(30000); //重要,如果主線程掛了,調(diào)用線程也停止了
    System.out.println("main Thread over");
  }
   
}

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

原文鏈接:http://blog.csdn.net/nature_fly088/article/details/54584802

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 好爽视频| 美女的让男人桶爽网站 | 日本xxxx19| 日韩欧美国产一区二区三区 | 日韩 欧美 国产 亚洲 中文 | 日本色播 | 歪歪漫画a漫入口 | 亚洲人的天堂男人爽爽爽 | 男生操女生漫画 | 白俄罗斯bbbsss | 天天看黄 | 邪恶肉肉全彩色无遮盖 | 亚洲欧美日韩一区成人 | 亚洲天堂2013| 四虎在线成人免费网站 | caoporn国产 | 九九九国产视频 | 女王脚奴vk | 日出水了特别黄的视频 | 国产精品视频一区二区三区 | 四虎精品视频在线永久免费观看 | 日韩精品视频观看 | 亚洲成片在线看 | 欧美国产日韩1区俺去了 | 九九热在线观看视频 | 日本一道本视频 | 调教全程肉动画片在线观看 | 91好色 | 超大阿力gaysex | 欧美人畜 | 美女沟厕撒尿全过程高清图片 | 福利姬 magnet | 蜜桃影像传媒破解版 | japanesexxxx在线播放 | 精品人人做人人爽久久久 | 色多多幸福宝 | 69日本xxxxxxxxx98| 国产亚洲福利一区二区免费看 | 四虎永久成人免费 | 国产理论片在线观看 | 91专区|