一个文本文件,格式如下:
<body>
<par dur="8s">
<text src="mms.txt" region="Text" />
<text src="mms1.txt" region="Text" /><text src="mms2.txt" region="Text" />
<text src="tex.txt" region="Text" />
</par>
<par dur="8s">
<img src="ly.jpg" region="Image" />
</par>
</body>
如何提取里面的所有文件名序列?如以上结果为mms.txt,mms1.txt,mms2.txt,tex.txt,ly.jpg
<body>
<par dur="8s">
<text src="mms.txt" region="Text" />
<text src="mms1.txt" region="Text" /><text src="mms2.txt" region="Text" />
<text src="tex.txt" region="Text" />
</par>
<par dur="8s">
<img src="ly.jpg" region="Image" />
</par>
</body>
如何提取里面的所有文件名序列?如以上结果为mms.txt,mms1.txt,mms2.txt,tex.txt,ly.jpg
import java.util.regex.*;
import java.io.*;public class GetFileName { /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//从文件里面读取内容到一个字符串,把要解析的内容放在文本文件中。
String fileContent=readFile("sample.txt");
//找字符串中的文件名
findNames(fileContent);
}
/**
* 从文件里面读取内容到一个字符串
* @param fileName
* @return
* @throws IOException
*/
public static String readFile(String fileName) throws IOException{
StringBuffer sbFileContent=new StringBuffer(500);
FileReader fr=new FileReader(fileName);
BufferedReader br=new BufferedReader(fr);
String lineContent=null;
while((lineContent=br.readLine())!=null){
sbFileContent.append(lineContent);
}
br.close();
fr.close();
return sbFileContent.toString();
}
/**
* 从字符串中抽取像文件名的字符串
* @param content
*/
public static void findNames(String content){
//这边是以引号作为分隔符限定的,如果是不带引号的html文件,正则表达式可能要复杂一点
Pattern p=Pattern.compile("[^\"]+\\.[^\"]+");
Matcher m=p.matcher(content);
while(m.find()){
System.out.println(m.group());
}
}}
把代码写得这么完整。
public static String readFile(String fileName)这个方法中的关闭操作应该写到finally里面,不然就没用了。