读取txt文件的内容

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class txttest {
	/**
	 * 读取txt文件的内容
	 * 
	 * @param file
	 *            想要读取的文件对象
	 * @return 返回文件内容
	 */
	public static String txt2String(File file) {
		StringBuilder result = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
				result.append(s + System.lineSeparator());
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}

	public static void main(String[] args) {
		File file = new File("D:/errlog.txt");
		System.out.println(txt2String(file));
		String[] strs = txt2String(file).split("\n");
		String[] ss = null;
		Map<String, String> map = new HashMap<String, String>();
		for (String string : strs) {
			ss = string.split(" ");// 每一行的数据
			for (String string2 : ss) {
				String[] sc = string2.split(":");// 属性
				System.out.println(sc[0] + "&" + sc[1]);
				String key = sc[0].trim();
				String value = sc[1].trim();
				map.put(key, value);//这里存进去的始终只有几个,存不全
			}
		}

		System.out.println(map);
		for (Entry<String, String> e : map.entrySet()) {
			System.out.println(e.getKey() + "" + e.getValue());

		}

		Iterator<Entry<String, String>> it = map.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
		}
		/*
		 * for (Entry<String, String> entry : map.entrySet()) {
		 * //Map.entry<Integer,String> 映射项(键-值对) 有几个方法:用上面的名字entry
		 * //entry.getKey() ;entry.getValue(); entry.setValue();
		 * //map.entrySet() 返回此映射中包含的映射关系的 Set视图。 System.out.println("key= " +
		 * entry.getKey() + " and value= " + entry.getValue()); } for (String v
		 * : map.values()) { System.out.println("value= " + v); }
		 */
	}
}

输出的内容:

id:1 name:张三 sex:男
id:2 name:李四 sex:男
id:3 name:王五 sex:女
id:4 name:赵六 sex:女
id:5 name:周七 sex:男

id&1
name&张三
sex&男

id&2
name&李四
sex&男

id&3
name&王五
sex&女

id&4
name&赵六
sex&女

id&5
name&周七
sex&男

{id=1, sex=男, name=周七, id=5}
id1
sex男
name周七
id5
key= id and value= 1
key= sex and value= 男
key= name and value= 周七
key= id and value= 5
errlog.txt
id:1 name:张三 sex:男
id:2 name:李四 sex:男
id:3 name:王五 sex:女
id:4 name:赵六 sex:女
id:5 name:周七 sex:男

哪位仁兄可以解答一下?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值