java在处理文件时BOM头的坑

最近项目中的需求是从一个文件中读取字符作为文件路径,再根据文件路径去读取指定文件的内容:
比如一个文件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头导致的

解决方案:

  1. 如果是可以直接操作的文件快速方法则是使用Notepad++等工具
    如:Encoding-Encoding in UTF-8 without BOM
  2. 在读取文件的时候去掉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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值