题:已知有个txt文件,在D:\menu.txt。
已知txt文件每行的格式均为
"AAAA_BBBB_..._CCCC","Y/N"
如果CCC为数字的话,该行数据过滤掉。
把过滤完的数据生成一个新的文件,或者打印出控制台。
例如
"TEST_ABC_12123","Y"
"TEST_BCD_DE_23242","N"
"TEST_BAD_DE","Y"
这三行数据就被过滤掉第一行跟第二行,保留第三行。
<span style="white-space:pre"> </span>@SuppressWarnings("resource")
public static void getTxt(String filePath) {
InputStreamReader inStreamReader=null;
try {
File file = new File(filePath);
if (!file.isFile() || !file.exists()) {
System.out.println("找不到指定文件!");
return;
} else {
inStreamReader = new InputStreamReader(new FileInputStream(file));
BufferedReader bufferedReader=new BufferedReader(inStreamReader);
String lineTxt=null;
int count = 0;
while((lineTxt=bufferedReader.readLine())!=null){
//截取
int lineLength=lineTxt.length();
String subLineTxt=lineTxt.substring(1, lineLength-5);
//分离
String[] subTxts=subLineTxt.split("_");
int subTxtsLength=subTxts.length;
//正则表达式判断最后一个是否为数字
String lastTxt=subTxts[subTxtsLength-1];
if(!lastTxt.matches("\\d*")){
count++;
System.out.println(lineTxt);
}
}
System.out.println("总共有"+count);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭InputStream
if(inStreamReader!=null){
try {
inStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}