JAVA文件读取和解析

前面两种可以设置编码格式。

1.第一种:xml文件的读取和Sax解析

InputSource inputSource = new InputSource(new FileInputStream(file));
inputSource.setEncoding("UTF-8");

List<Map<String, String>> list = reader.getList(file);

public static List<Map<String, String>> getList(File file) throws Exception{
InputSource inputSource = new InputSource(new FileInputStream(file));
inputSource.setEncoding("UTF-8");
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();
XML_LOG_READ_OUT reader = new XML_LOG_READ_OUT();
sp.parse(inputSource, reader);
return reader.getList();
}

2.第二种:TXT文件读取和解析

InputStreamReader read = new InputStreamReader(new FileInputStream(file),"UTF-8");
BufferedReader br= new BufferedReader(read);//BufferedReader读取文件
String s = null;
int i = 0;
while((s = br.readLine()) != null){
if(i > 0){
Map<String, String> map = new HashMap<String, String>();
String[] str = s.split(" ");//根据tab键划分

}

}

i++;
}
br.close();

}

3,第三种txt文件读取

BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
int i = 0;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
if(i>0){

String[] str = s.split(" ");
String time = str[0].replace("/", "-");
SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdfInput.parse(time);
result.append(System.lineSeparator()+"时间是:"+sdfInput.format(date));

}

i++;
}
br.close();

}

原文地址:https://www.cnblogs.com/ouyanxia/p/6419859.html