java NIO 处理 txt文件

想到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);
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值