java NIO 处理 txt文件

来源:互联网 发布:mac上新建文件夹 编辑:程序博客网 时间:2024/05/16 18:31
想到apache和tomcat 的http.conf 配置文件,心血来潮, 使用java noi包来解析txt文件,可以做到参数化配置。仅作记录免得忘记,代码示例如下NIO处理txt文件

package com.i2f.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author angelo
 * @date 2011-12-19
 */
public class TxtParser {
 private String[] fileTypes = { "txt" };

 public String[] getFileTypes() {
  return fileTypes;
 }

 public String readText(File file, String charset) throws Exception {
  Map<String, String> parameter = new HashMap<String, String>();
  FileChannel inChannel = null;
  ByteBuffer bb = ByteBuffer.allocate(512);
  Charset cs = Charset.forName(charset);
  StringBuffer sb = new StringBuffer();
  FileInputStream inFile = null;
  CharBuffer cb = null;
  try {
   inFile = new FileInputStream(file);
   inChannel = inFile.getChannel();
   while (inChannel.read(bb) != -1) {
    bb.flip();
    cb = cs.decode(bb);
    String[] strs = cb.toString().split("=");
    parameter.put(strs[0], strs[1]);
    sb.append(cb);
    bb.clear();
   }
  } finally {
   if (inFile != null)
    try {
     inFile.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
  }
  return sb.toString();
 }

 public static void main(String[] s) throws Exception {
  long total = 0L;
  for (int i = 0; i < 1; i++) {
   long start = System.currentTimeMillis();
   System.out.println(new TxtParser().readText(
     new File("d:/test2.txt"), "utf-8"));

   total += System.currentTimeMillis() - start;

  }
  System.out.print("耗时:" + total);
 }
}

原创粉丝点击