不管是用字节流还是字符流,都可以轻松的进行文件读取。当然,它们对乱码问题的处理方式是不同的。
1. 字节流
- * @param args
- */
- public static void main(String[] args) {
- try {
- InputStream in = new BufferedInputStream(new FileInputStream("D:/temp/a.txt"));
- int c;
- StringBuffer sb = new StringBuffer();
- while ((c = in.read())>0){
- sb.append((char)c);
- }
- String response = new String(sb.toString().getBytes("iso-8859-1"), "gb2312");
- System.out.print(response);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
处理方法:对读取到的文件内容进行字符编码转换
2. 字符流
- * Read file's content
- *
- * @param fileAndPath String the file and path
- * @return String the file's content
- */
- public static String readFile (String fileAndPath) {
- String fileContent = "";
- File file = new File(fileAndPath);
- if (file.isFile() && file.exists()) {
- try {
- InputStreamReader in = new InputStreamReader(new FileInputStream(file), "gb2312");
- BufferedReader bf = new BufferedReader(in);
- String temp;
- while ((temp=bf.readLine()) !=null) {
- fileContent += temp+"\n";
- }
- bf.close();
- in.close();
- }catch (FileNotFoundException e) {
- System.out.println("File not found");
- e.printStackTrace();
- } catch (IOException e) {
- System.out.println("Something wrong when reading file");
- e.printStackTrace();
- }
- }
- return fileContent;
- }
处理方法: 读取文件时,用字符流类InputStreamReader进行编码转换
3. Linux 平台下
暂时没有碰到这样的问题。但是据说在Linux平台下,用字符流读取会有乱码问题。
-----------------------------------------------------
项目中要求读取数据文件通过java程序导入数据库,数据文件是ANSI编码格式的,在windows环境中没有什么问题,windows会自动将编码转换成为gb2312的,但是在linux平台上由于多语言,使用InputStreamReader由字节码转换为字符码的时候会容易产生无法正确转换的乱码,解决方法为读取的时候采用iso-8859-1格式读取,在程序中再次转码。
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(filename),"iso-8859-1"));
String line = reader.readLine();
line = new String("iso-8859-1","gb2312");