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);  
                }  
        } 



所以,在讀取文件的時候就得進行編碼設置,而不是讀完文件輸出時再設置編碼!

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *