从文本中读入文件时,要是文本存在中文,用字节流的形式读取文件,即使写入如下代码:
这样进行了字符集的改变,但也不能正确读取文件中的中文。而文本中都是字符串类型的数据,所以可以用字符流读取文件,代码如下:
- StringBuffer sqlSb = new StringBuffer();
- byte[] buff = new byte[1024];
- int byteRead = 0;
- while ((byteRead = sqlFileIn.read(buff)) != -1) {
- sqlSb.append(new String(buff, 0, byteRead));
- }
- String temp2 = new String(sqlSb.toString().getBytes("UTF-8"), "UTF-8");
- System.out.println("读出文件信息:"+temp2);
这样进行了字符集的改变,但也不能正确读取文件中的中文。而文本中都是字符串类型的数据,所以可以用字符流读取文件,代码如下:
- File file=new File(sqlFile);
- BufferedReader reader = null;
- reader = new BufferedReader(new FileReader(file));
- String str = null;
- while ((str = reader.readLine()) != null) {
- System.out.println(str);
- sqlSb.append(str+"\r\n");
- }
所以,当要读取文本中存在中文的文本时,最好要用字符流读取文件!
一定要记得关闭流,它会释放文件句柄并允许其他人访问文件。
转载自:http://panlianghui-126-com.iteye.com/blog/1472191