最近项目中的需求是从一个文件中读取字符作为文件路径,再根据文件路径去读取指定文件的内容:
比如一个文件test.txt的内容是
wenjian1.txt
wenjian2.txt
wenjian3.txt
现在要根据test.txt的文件获取wenjian1.txt、wenjian2.txt、wenjian3.txt的文件名
//根据文件路径获取文件每一行的内容,存入list集合中
public List<String> fileContentList(String filePath){
List<String> list = new ArrayList<String>();
String encoding="UTF-8";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
list.add(lineTxt);
}
read.close();
} else {
System.out.println("找不到指定的文件");
}
}
在调用fileContentList(“d:/test.txt”);则返回的list集合为[“wenjian1.txt”,“wenjian2.txt”,“wenjian3.txt”],然后根据list的内容去同级目录下读取三个文件的内容,可以再次调用fileContentList(“d:/wenjian1.txt”);
问题来了
java.io.FileNotFoundException: d:/wenjian1.txt (系统找不到指定的路径。)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at com.yaohong.test.InputStreamTest.fileInputStream(InputStreamTest.java:13)
可是在指定目录下确实找的到这个wenjian1.txt文件
后面发现是txt文件的BOM头导致的
解决方案:
- 如果是可以直接操作的文件快速方法则是使用Notepad++等工具
如:Encoding-Encoding in UTF-8 without BOM - 在读取文件的时候去掉BOM头内容
public static InputStream getInputStream(InputStream in) throws IOException {
PushbackInputStream testin = new PushbackInputStream(in);
int ch = testin.read();
if (ch != 0xEF) {
testin.unread(ch);
} else if ((ch = testin.read()) != 0xBB) {
testin.unread(ch);
testin.unread(0xef);
} else if ((ch = testin.read()) != 0xBF) {
throw new IOException("文件异常");
}
return testin;
}
则需修改文件输入流的读取方式为:
InputStreamReader read = new InputStreamReader(getInputStream(new FileInputStream(file)),encoding);