1. 程式人生 > >java 解析txt,conf 檔案

java 解析txt,conf 檔案

@SuppressWarnings("unchecked")
 public String[] readfile(String filepath) throws Exception {
  FileReader fr = new FileReader(filepath);
  // 將無法識別的位元組賦值為'?'
  int c = 63;
  String errmessage = "檔案編碼不是GBK,不能解析";
  try {
   // 從檔案中讀取一個字元
   c = fr.read();
  } catch (Exception e) {
   try {
    fr.skip(1);
   } catch (Exception ex) {
    throw new Exception(errmessage, ex);
   }
   c = 63;
  }
  StringBuffer sb = new StringBuffer();
  List list = new ArrayList();
  while (c != -1) {
   // 遇到回車符時儲存該行內容,重新整理快取
   if (c == 10) {
    list.add(sb.toString());
    sb = new StringBuffer();
    try {
     // 從檔案中繼續讀取資料
     c = fr.read();
    } catch (Exception e) {
     try {
      fr.skip(1);
     } catch (Exception ex) {
      throw new Exception(errmessage, ex);
     }
     c = 63;
    }
    continue;
   }
   sb.append((char) c);
   try {
    // 從檔案中繼續讀取資料
    c = fr.read();
   } catch (Exception e) {
    try {
     fr.skip(1);
    } catch (Exception ex) {
     throw new Exception(errmessage, ex);
    }
    c = 63;
   }
  }
  // 儲存最後一行內容
  if (c == -1 && sb.length() > 0) {
   list.add(sb.toString());
  }
  fr.close();
  // 返回從文字檔案中讀取的內容
  Object[] obj = list.toArray();
  String[] objs = new String[obj.length];
  for (int i = 0; i < obj.length; i++) {
   objs[i] = (String) obj[i];
  }
  return objs;
 }