2 回答

TA貢獻1752條經驗 獲得超4個贊
我寫了一個demo,希望能幫到你
package com.wenqiang.regex;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* 其中每個文本行前四個字母稱為行類型,每個文本塊從HEDR行開始到下個HEDR結束(不含下個HEDR行),最后一個TLRL是文件結束標志。
* 約束條件:
* 1、處理掉文件不存在、文件打開或讀取失敗等異常。
* 2、忽略掉空行。
* 3、每個文本行前四個字符必須由三個大寫英文字母加一個大寫英文字母或一個數字組成,要求用正則表達式進行驗證。
* 4、如果文件末尾沒有TLRL行,則返回空ArrayList,即認為該文件無效。
* 請編寫一個方法,返回由若干個文件塊組成的ArrayList,即其中每個元素是文本塊,每個文本塊也定義成一個ArrayList.
* @author wenqiang
*
*/
public class MessageHander {
private final static String reg = "^[A-Z]{3}[A-Z0-9]+";
public boolean pathIsExist(String path){
File file = new File(path);
return fileIsExist(file);
}
public boolean fileIsExist(File file){
return file.exists();
}
public List<ArrayList<String>> handerMsg(String filepath){
List<ArrayList<String>> msgList = new ArrayList<ArrayList<String>>();
if(!pathIsExist(filepath)){
System.out.println("文件不存在!--PATH");
}else{
File file = new File(filepath);
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
String temp = "";
ArrayList<String> tempList = null;
try {
while(true){
temp = br.readLine();
if("TLRL".equals(temp)){
if(tempList!=null){
msgList.add(tempList);
}
System.out.println("文件讀取結束--TLRL!");
break;
}else if(temp==null){
if(tempList!=null){
msgList.add(tempList);
}
System.out.println("文件讀取結束--NULL!");
break;
}else{
if("".equals(temp)){
}else if(Pattern.matches(reg, temp.trim())&&"HED".equals(temp.substring(0, 3))){
if(tempList!=null){
msgList.add(tempList);
}
tempList = new ArrayList<String>();
tempList.add(temp);
}else{
tempList.add(temp);
}
}
}
} catch (IOException e) {
System.out.println("文件讀取失敗--IO!");
e.printStackTrace();
return msgList;
}
} catch (FileNotFoundException e) {
System.out.println("文件打不開!--FILE");
e.printStackTrace();
return msgList;
}finally{
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return msgList;
}
public static void main(String[] args) {
String filepath = "e:/file.txt";
List<ArrayList<String>> resultList = new MessageHander().handerMsg(filepath);
System.out.println(resultList.size());
System.out.println(resultList.toString());
//System.out.println(Pattern.matches(reg, "HEDRA"));
//System.out.println("HED".equals("HEDRA".substring(0, 3)));
}
}

TA貢獻1852條經驗 獲得超7個贊
約束1:打開文件或者讀取文件失敗要捕獲異常信息用try catch就好了
約束2:while((line = br.readLine()) ==null)不讀取這行
約束3:用正則驗證前四個字符,每次讀取一行,截取前四個九OK了,至于正則表達式,網上搜一下
約束4:while((sc.hasNextLine()&&(line=sc.nextLine())!=null)){
if(!sc.hasNextLine())
System.out.println(line);判斷line的值是否是TLRL
}
最后的意思就是:你每次讀取一個HEDR開頭的到head結尾的數據,就把他放在arraylist中
添加回答
舉報