最近项目有了新需求,需要把指定目录下的xml文件解析成JSON字符串并存储到mongoDB中。我使用了org.dom4j的解析方法,在运行时发现报错:前言中不允许有内容。百度后得知是因为文件带bom头,解析的时候就会报错,需要去掉bom头。结果网上的方法让人啼笑皆非,用EditPuls来转换成无bom编码。我就纳闷了,难道项目运行时,还要人工一个个的去这样操作吗?肯定不行,得用java的方式去自动化解决。后来找到了apache.common.io的BomInputSteam类,可以跳过bom头读取。现分享代码段。
-
try {
-
FileInputStream
fis
=
new
FileInputStream(path);
-
BOMInputStream
bis
=
new
BOMInputStream(fis);
-
String
charset
= bis.getBOMCharsetName();
-
InputStreamReader
isr
=
new
InputStreamReader(bis);
-
if(StringUtils.hasText(charset)) {
-
isr =
new
InputStreamReader(bis,charset);
-
}
-
BufferedReader
reader
=
new
BufferedReader(isr);
-
List<String> list =
new
ArrayList<String>();
-
String line;
-
try {
-
while ((line = reader.readLine()) !=
null) {
-
list.add(line);
-
}
-
}
catch (IOException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
return list;
-
}
catch (FileNotFoundException fn) {
-
-
}
catch (IOException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
return
null;