当前位置:编程学习 > JAVA >>

JAVA 打开文件乱码 解决办法

String Data_Path = "D:/file_jiucool.txt";  
        File file = new File(Data_Path);  
        String line= "";  
        if(file.exists()){        
            FileReader reader = new FileReader(Data_Path);    
            BufferedReader bufferedreader= new BufferedReader(reader);  
            while((line = bufferedreader.readLine())!=null){  
                    line = new String(line.getBytes(), "UTF-8");  
                    System.out.println(line);  
                }  
        } 

上述代码中,设置为GBK、GB2312 时全部为乱码,设置为UTF-8时,最后一个汉字为乱码,是不是很让人郁闷?正确代码如下:

String Data_Path = "D:/file_jiucool.txt";  
        File file = new File(Data_Path);  
        String line= "";  
        if(file.exists()){        
            //FileReader reader = new FileReader(Data_Path);      
            //BufferedReader bufferedreader= new BufferedReader(reader);  
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");  
            BufferedReader bufferedreader = new BufferedReader(isr);  
            while((line = bufferedreader.readLine())!=null){  
                    //line = new String(line.getBytes(), "UTF-8");  
                    System.out.println(line);  
                }  
        } 


所以,在读取文件的时候就得进行编码设置,而不是读完文件输出时再设置编码!

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,