Java 文件流,正则表达式,HashMap

简述:

读取一个txt,从中获取一个大String,然后用Java的正则表达式解析,存入一个HashMap之后输出


知识点:

1. Java的文件流(注意查看当前文件路径System.getProperty("user.dir");

2. String字符串的正则解析

       1_   圆括号会细分为Matcher.group(1),Matcher.group(2) etc 的元素

       2_   非贪婪模式,使用"?"符号,找到第一个匹配[ ' ]的一段字符串

3. HashMap的使用及遍历


message.txt

{
1: 'aas31df',
 2: 'dfsf:se.fae',
 3: 'gold metal AL'}


代码:

package test.stringTest;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestStringOpertion {

	public static String ReadFile(String filePath) throws IOException{
		FileInputStream fileInputStream = new FileInputStream(filePath);
		InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String message = "";
		String line = "";
		while((line = bufferedReader.readLine()) != null)
			message += line;
		return message;
	}
	
	public static void main(String[] args) throws IOException{
//		System.out.print(System.getProperty("user.dir"));
		String str = ReadFile("./src/test/stringTest/message.txt");
		
		
		Pattern pattern = Pattern.compile("([0-9]+): '(.*?)'");
		Matcher matcher = pattern.matcher(str);
		
		HashMap<Integer, String> keyValueMap = new HashMap<Integer, String>();
		while(matcher.find()){
			String keyStr = matcher.group(1);
			String valueStr = matcher.group(2);
			keyValueMap.put(Integer.parseInt(keyStr), valueStr);
		}
		
		//遍历hashmap方法一
		System.out.println("遍历hashmap方法一, ");
		Iterator<Integer> it = keyValueMap.keySet().iterator();
		while(it.hasNext()){
			Integer key = it.next();
			String value = keyValueMap.get(key);
			System.out.println(key + " = " + value);
		}
		
		//遍历hashmap方法二
		System.out.println("\n遍历hashmap方法二,");
		for(Object key : keyValueMap.keySet()){
			System.out.println(key + " = " + keyValueMap.get(key));
		}
	}
}

输出:

Java 文件流,正则表达式,HashMap_第1张图片

你可能感兴趣的:(Java 文件流,正则表达式,HashMap)