最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 正文

读写properties配置文件时带上注释

来源:动视网 责编:小OO 时间:2025-09-29 04:54:34
文档

读写properties配置文件时带上注释

Java使用jdk自带的类操作properties配置文件,特别是更改文件后会把注释全部删掉,再读时会不知道配置是什么意思,下面这个类是我自己写的不删除注释操作properties的类。importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.
推荐度:
导读Java使用jdk自带的类操作properties配置文件,特别是更改文件后会把注释全部删掉,再读时会不知道配置是什么意思,下面这个类是我自己写的不删除注释操作properties的类。importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.
Java使用jdk自带的类操作properties配置文件,特别是更改文件后会把注释全部删掉,再读时会不知道配置是什么意思,下面这个类是我自己写的不删除注释操作properties的类。

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStreamWriter;

import java.io.Reader;

import java.io.Writer;

import java.util.Date;

import java.util.HashMap;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.Properties;

import java.util.Set;

/**

 * 读取Properties配置文件,同时读出注释。 注释在jdk源方法的LineReader中忽略,

*

 * 此处改造LineReader,并添加存放的变量map

*

 * 同时新加了getPropertyAndComment(key)方法,返回的字符串:如果有注释则为:值#注释,如果无注释,则为:值

*

 * 写入Properties方法是直接从网上下载的方法

 * @author liuwei

 * */

public class ReadAndWriteProperties extends Properties {

 /**

  * 

  */

 private static final long serialVersionUID = 1L;

 public static void main(String[] args) throws Exception {

  //写入

//  ReadAndWriteProperties properties = new ReadAndWriteProperties();

//  FileOutputStream fileOutputStream = new FileOutputStream(

//    "D:/test.properties", true);

//  OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);

//  for (int i = 1; i < 10; i++) {

//   String string = String.valueOf(i);

//   properties.setP("Name" + string, string, "the name of " + string);

//  }

//  properties.orderStore(writer, "This is a test process...");

  //读取

  ReadAndWriteProperties props = new ReadAndWriteProperties();

  File file = new File("E:\\\est\\\\CemsMiddleware.properties");

  InputStream in = new FileInputStream(file);

  props.load(in);

  Set keySet = props.keySet();

  Object value = null;

  for (Object key : keySet) {

   // value = props.getProperty((String) key);

   value = props.getPropertyAndComment((String) key);

   System.out.println(key + ":" + value);

  }

 }

 private LinkedHashMap commentMap = new LinkedHashMap();

 //首先是写相关--------------------------------------

 /**

  * Constructor.

  */

 public ReadAndWriteProperties() {

  super();

 }

 /**

  * Constructor.

  * 

  * @param properties

 

  */

 public ReadAndWriteProperties(Properties properties) {

  super(properties);

  // Initialize the comment.

  Iterator iterator = properties.keySet().iterator();

  while (iterator.hasNext()) {

   Object key = iterator.next();

   this.commentMap.put((String) key, null);

  }

 }

 /**

  * Add comment to a property.

  * 

  * @param key

 

  * @param comment

 

  * @return true => add it false => don't have this key.

  */

 public boolean addComment(String key, String comment) {

  if (this.contains(key)) {

   this.commentMap.put(key, comment);

   return true;

  }

  return false;

 }

 /**

  * To set property.

  * 

  * @param key

 

  * @param value

 

  * @param comment

 

  */

 public void setP(String key, String value, String comment) {

  this.commentMap.put(key, comment);

  this.setProperty(key, value);

 }

 public void getP(String key, String value, String comment) {

  this.commentMap.put(key, comment);

  this.setProperty(key, value);

 }

 /**

  * To output according to the order of input.

  * 

  * @param writer

 

  * @param comments

 

  * @throws IOException

 

  */

 public void orderStore(Writer writer, String comments) throws IOException {

  BufferedWriter bufferedWriter = (writer instanceof BufferedWriter) ? (BufferedWriter) writer

    : new BufferedWriter(writer);

  if (comments != null) {

   ReadAndWriteProperties.writeComments(bufferedWriter, comments);

  }

  bufferedWriter.write("#" + new Date().toString());

  bufferedWriter.newLine();

  bufferedWriter.newLine();

  synchronized (this) {

   Iterator iterator = this.commentMap.keySet().iterator();

   while (iterator.hasNext()) {

    String key = iterator.next();

    String value = this.getProperty(key);

    String comment = this.commentMap.get(key);

    key = saveConvert(key, true, false);

    value = saveConvert(value, false, false);

    key = saveConvert(key, true, false);

    if (comment != null && !comment.equals("")) {

     writeComments(bufferedWriter, comment);

    }

    bufferedWriter.write(key + "=" + value);

    bufferedWriter.newLine();

    bufferedWriter.newLine();

   }

  }

  bufferedWriter.flush();

 }

 private String saveConvert(String theString, boolean escapeSpace,

   boolean escapeUnicode) {

  int len = theString.length();

  int bufLen = len * 2;

  if (bufLen < 0) {

   bufLen = Integer.MAX_VALUE;

  }

  StringBuffer outBuffer = new StringBuffer(bufLen);

  for (int x = 0; x < len; x++) {

   char aChar = theString.charAt(x);

   // Handle common case first, selecting largest block that

   // avoids the specials below

   if ((aChar > 61) && (aChar < 127)) {

    if (aChar == '\\\\') {

     outBuffer.append('\\\\');

     outBuffer.append('\\\\');

     continue;

    }

    outBuffer.append(aChar);

    continue;

   }

   switch (aChar) {

   case ' ':

    if (x == 0 || escapeSpace)

     outBuffer.append('\\\\');

    outBuffer.append(' ');

    break;

   case '\':

    outBuffer.append('\\\\');

    outBuffer.append('t');

    break;

   case '\\n':

    outBuffer.append('\\\\');

    outBuffer.append('n');

    break;

   case '\\r':

    outBuffer.append('\\\\');

    outBuffer.append('r');

    break;

   case '\\f':

    outBuffer.append('\\\\');

    outBuffer.append('f');

    break;

   case '=': // Fall through

   case ':': // Fall through

   case '#': // Fall through

   case '!':

    outBuffer.append('\\\\');

    outBuffer.append(aChar);

    break;

   default:

    if (((aChar < 0x0020) || (aChar > 0x007e)) & escapeUnicode) {

     outBuffer.append('\\\\');

     outBuffer.append('u');

     outBuffer.append(toHex((aChar >> 12) & 0xF));

     outBuffer.append(toHex((aChar >> 8) & 0xF));

     outBuffer.append(toHex((aChar >> 4) & 0xF));

     outBuffer.append(toHex(aChar & 0xF));

    } else {

     outBuffer.append(aChar);

    }

   }

  }

  return outBuffer.toString();

 }

 /*

  * !!!Copy from java source code.

  */

 private static void writeComments(BufferedWriter bw, String comments)

   throws IOException {

  bw.write("#");

  int len = comments.length();

  int current = 0;

  int last = 0;

  char[] uu = new char[6];

  uu[0] = '\\\\';

  uu[1] = 'u';

  while (current < len) {

   char c = comments.charAt(current);

   if (c > '\ÿ' || c == '\\n' || c == '\\r') {

    if (last != current)

     bw.write(comments.substring(last, current));

    if (c > '\ÿ') {

     uu[2] = toHex((c >> 12) & 0xf);

     uu[3] = toHex((c >> 8) & 0xf);

     uu[4] = toHex((c >> 4) & 0xf);

     uu[5] = toHex(c & 0xf);

     bw.write(new String(uu));

    } else {

     bw.newLine();

     if (c == '\\r' && current != len - 1

       && comments.charAt(current + 1) == '\\n') {

      current++;

     }

     if (current == len - 1

       || (comments.charAt(current + 1) != '#' && comments

         .charAt(current + 1) != '!'))

      bw.write("#");

    }

    last = current + 1;

   }

   current++;

  }

  if (last != current)

   bw.write(comments.substring(last, current));

  bw.newLine();

 }

 /*

  * !!! Copy from java source code.

  */

 private static char toHex(int nibble) {

  return hexDigit[(nibble & 0xF)];

 }

 /** A table of hex digits */

 private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6',

   '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

 // 以下是读相关-----------------------------------------------------

 Map comments = new HashMap();

 public String getPropertyAndComment(String key) {

  Object oval = super.get(key);

  String sval = (oval instanceof String) ? (String) oval : null;

  String coment = comments.get(key);

  String co = coment == null ? "" : coment;

  // System.out.println(key+":"+coment);

  return ((sval == null) && (defaults != null)) ? defaults

    .getProperty(key) + co : sval + co;

 }

 /**

  * jdk源方法

  * */

 public synchronized void load(InputStream inStream) throws IOException {

  load0(new LineReader(inStream));

 }

 /**

  * jdk源方法,经改造后不忽略注释

  * */

 private void load0(LineReader lr) throws IOException {

  char[] convtBuf = new char[1024];

  int limit;

  int keyLen;

  int valueStart;

  char c;

  boolean hasSep;

  boolean precedingBackslash;

  String coment = "";

  while ((limit = lr.readLine()) >= 0) {

   c = 0;

   keyLen = 0;

   valueStart = limit;

   hasSep = false;

   precedingBackslash = false;

   // 注释相关

   if ('#' == lr.lineBuf[0]) {

    coment = loadConvert(lr.lineBuf, 0, limit, convtBuf);

    coment = new String(coment.getBytes("iso8859-1"), "utf-8");

    // System.out.println(coment);

    continue;

   }

   // System.out.println("line=<" + new String(lineBuf, 0, limit) +

   // ">");

   while (keyLen < limit) {

    c = lr.lineBuf[keyLen];

    // need check if escaped.

    if ((c == '=' || c == ':') && !precedingBackslash) {

     valueStart = keyLen + 1;

     hasSep = true;

     break;

    } else if ((c == ' ' || c == '\' || c == '\\f')

      && !precedingBackslash) {

     valueStart = keyLen + 1;

     break;

    }

    if (c == '\\\\') {

     precedingBackslash = !precedingBackslash;

    } else {

     precedingBackslash = false;

    }

    keyLen++;

   }

   while (valueStart < limit) {

    c = lr.lineBuf[valueStart];

    if (c != ' ' && c != '\' && c != '\\f') {

     if (!hasSep && (c == '=' || c == ':')) {

      hasSep = true;

     } else {

      break;

     }

    }

    valueStart++;

   }

   String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);

   String value = loadConvert(lr.lineBuf, valueStart, limit

     - valueStart, convtBuf);

   put(key, value);

   // 注释相关

   if (coment != null && coment.length() > 0) {

    comments.put(key, coment);

    coment = "";// 重置注释

   }

  }

 }

 /**

  * jdk源方法

  * */

 private String loadConvert(char[] in, int off, int len, char[] convtBuf) {

  if (convtBuf.length < len) {

   int newLen = len * 2;

   if (newLen < 0) {

    newLen = Integer.MAX_VALUE;

   }

   convtBuf = new char[newLen];

  }

  char aChar;

  char[] out = convtBuf;

  int outLen = 0;

  int end = off + len;

  while (off < end) {

   aChar = in[off++];

   if (aChar == '\\\\') {

    aChar = in[off++];

    if (aChar == 'u') {

     // Read the xxxx

     int value = 0;

     for (int i = 0; i < 4; i++) {

      aChar = in[off++];

      switch (aChar) {

      case '0':

      case '1':

      case '2':

      case '3':

      case '4':

      case '5':

      case '6':

      case '7':

      case '8':

      case '9':

       value = (value << 4) + aChar - '0';

       break;

      case 'a':

      case 'b':

      case 'c':

      case 'd':

      case 'e':

      case 'f':

       value = (value << 4) + 10 + aChar - 'a';

       break;

      case 'A':

      case 'B':

      case 'C':

      case 'D':

      case 'E':

      case 'F':

       value = (value << 4) + 10 + aChar - 'A';

       break;

      default:

       throw new IllegalArgumentException(

         "Malformed \\\ encoding.");

      }

     }

     out[outLen++] = (char) value;

    } else {

     if (aChar == 't')

      aChar = '\';

     else if (aChar == 'r')

      aChar = '\\r';

     else if (aChar == 'n')

      aChar = '\\n';

     else if (aChar == 'f')

      aChar = '\\f';

     out[outLen++] = aChar;

    }

   } else {

    out[outLen++] = aChar;

   }

  }

  return new String(out, 0, outLen);

 }

 class LineReader {

  /**

   * jdk源方法

   * */

  public LineReader(InputStream inStream) {

   this.inStream = inStream;

   inByteBuf = new byte[8192];

  }

  /**

   * jdk源方法

   * */

  public LineReader(Reader reader) {

   this.reader = reader;

   inCharBuf = new char[8192];

  }

  byte[] inByteBuf;

  char[] inCharBuf;

  char[] lineBuf = new char[1024];

  int inLimit = 0;

  int inOff = 0;

  InputStream inStream;

  Reader reader;

  /**

   * jdk源方法,但经过改造,不再忽略注释

   * */

  int readLine() throws IOException {

   int len = 0;

   char c = 0;

   boolean skipWhiteSpace = true;

   boolean isCommentLine = false;

   boolean isNewLine = true;

   boolean appendedLineBegin = false;

   boolean precedingBackslash = false;

   boolean skipLF = false;

   while (true) {

    if (inOff >= inLimit) {

     inLimit = (inStream == null) ? reader.read(inCharBuf)

       : inStream.read(inByteBuf);

     inOff = 0;

     if (inLimit <= 0) {

      if (len == 0 || isCommentLine) {

       return -1;

      }

      return len;

     }

    }

    if (inStream != null) {

     // The line below is equivalent to calling a

     // ISO8859-1 decoder.

     c = (char) (0xff & inByteBuf[inOff++]);

    } else {

     c = inCharBuf[inOff++];

    }

    if (skipLF) {

     skipLF = false;

     if (c == '\\n') {

      continue;

     }

    }

    if (skipWhiteSpace) {

     if (c == ' ' || c == '\' || c == '\\f') {

      continue;

     }

     if (!appendedLineBegin && (c == '\\r' || c == '\\n')) {

      continue;

     }

     skipWhiteSpace = false;

     appendedLineBegin = false;

    }

    if (isNewLine) {

     isNewLine = false;

     if (c == '#' || c == '!') {

      // isCommentLine = true;

      // continue;

     }

    }

    if (c != '\\n' && c != '\\r') {

     lineBuf[len++] = c;

     if (len == lineBuf.length) {

      int newLength = lineBuf.length * 2;

      if (newLength < 0) {

       newLength = Integer.MAX_VALUE;

      }

      char[] buf = new char[newLength];

      System.arraycopy(lineBuf, 0, buf, 0, lineBuf.length);

      lineBuf = buf;

     }

     // flip the preceding backslash flag

     if (c == '\\\\') {

      precedingBackslash = !precedingBackslash;

     } else {

      precedingBackslash = false;

     }

    } else {

     // reached EOL

     if (isCommentLine || len == 0) {

      isCommentLine = false;

      isNewLine = true;

      skipWhiteSpace = true;

      len = 0;

      continue;

     }

     if (inOff >= inLimit) {

      inLimit = (inStream == null) ? reader.read(inCharBuf)

        : inStream.read(inByteBuf);

      inOff = 0;

      if (inLimit <= 0) {

       return len;

      }

     }

     if (precedingBackslash) {

      len -= 1;

      // skip the leading whitespace characters in following

      // line

      skipWhiteSpace = true;

      appendedLineBegin = true;

      precedingBackslash = false;

      if (c == '\\r') {

       skipLF = true;

      }

     } else {

      return len;

     }

    }

   }

  }

 }

}

文档

读写properties配置文件时带上注释

Java使用jdk自带的类操作properties配置文件,特别是更改文件后会把注释全部删掉,再读时会不知道配置是什么意思,下面这个类是我自己写的不删除注释操作properties的类。importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.
推荐度:
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

Top