【转】Java IO 读取文件中的乱码问题

无论是用字节流仍是字符流,均可以轻松的进行文件读取。固然,它们对乱码问题的处理方式是不一样的。 java

1. 字节流 linux

/**  
     * @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进行编码转换 windows

 

3. Linux 平台下 app

暂时没有碰到这样的问题。可是听说在Linux平台下,用字符流读取会有乱码问题。 编码

----------------------------------------------------- spa

项目中要求读取数据文件经过java程序导入数据库,数据文件是ANSI编码格式的,在windows环境中没有什么问题,windows会自动将编码转换成为gb2312的,可是在linux平台上因为多语言,使用InputStreamReader由字节码转换为字符码的时候会容易产生没法正确转换的乱码,解决方法为读取的时候采用iso-8859-1格式读取,在程序中再次转码。 code

   BufferedReader reader = new BufferedReader(new InputStreamReader(
     new FileInputStream(filename),"iso-8859-1"));
get

    String line = reader.readLine(); io

    line = new String("iso-8859-1","gb2312");

相关文章
相关标签/搜索