搜尋
首頁Javajava教程三種方法實作java字元轉碼的實例程式碼總結

這篇文章主要介紹了java字元轉碼的三種方法總結及實例的相關資料,需要的朋友可以參考下

java字元轉碼:三種方法

轉碼成功的前提:解碼後無亂碼

#轉碼流程:檔案(gbk)-->解碼--> ;編碼--->檔案(utf-8) 

附註:如有問題請留言 

下面特定的實例

 方法一:Java.lang.String

#
//用于解码的构造器: 
String(byte[] bytes, int offset, int length, String charsetName)  
String(byte[] bytes, String charsetName)  
 
用于编码的方法: 
byte[] getBytes(String charsetName) //使用指定字符集进行编码 
 byte[] getBytes() //使用系统默认字符集进行编码
public void convertionString() throws UnsupportedEncodingException{ 
    String s = "清山"; 
    byte[] b = s.getBytes("gbk");//编码 
    String sa = new String(b, "gbk");//解码:用什么字符集编码就用什么字符集解码 
    System.out.println(sa); 
     
    b = sa.getBytes("utf-8");//编码 
    sa = new String(b, "utf-8");//解码 
    System.err.println(sa); 
  }

方法二:java.io.InputStreamReader/OutputStreamWriter :橋接器轉換 

package com.qingshan.io; 
 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.io.UnsupportedEncodingException; 
 
/** 
 * <pre class="brush:php;toolbar:false"> 
 * 使用java.io桥转换:对文件进行转码 
 * 
   * 
   * 2012 Qingshan Group 版权所有   * 
   * @author thetopofqingshan   * @version 1.0.0   * @since  JDK 1.5   * @date  2012-4-28   */  public class CharsetConvertion {    private FileInputStream fis;// 文件输入流:读取文件中内容    private InputStream is;    private InputStreamReader isr;    private OutputStream os;    private OutputStreamWriter osw;//写入    private char[] ch = new char[1024];    public void convertionFile() throws IOException{      is = new FileInputStream("C:/项目进度跟踪.txt");//文件读取      isr = new InputStreamReader(is, "gbk");//解码      os = new FileOutputStream("C:/项目进度跟踪_utf-8.txt");//文件输出      osw = new OutputStreamWriter(os, "utf-8");//开始编码      char[] c = new char[1024];//缓冲      int length = 0;      while(true){        length = isr.read(c);        if(length == -1){          break;        }        System.out.println(new String(c, 0, length));        osw.write(c, 0, length);        osw.flush();      }          }        public void convertionString() throws UnsupportedEncodingException{      String s = "清山集团";      byte[] b = s.getBytes("gbk");//编码      String sa = new String(b, "gbk");//解码:用什么字符集编码就用什么字符集解码      System.out.println(sa);            b = sa.getBytes("utf-8");//编码      sa = new String(b, "utf-8");//解码      System.err.println(sa);    }              /**     * 
 
   * 关闭所有流 
   * 
     *     */    public void close(){      if(isr != null){        try {          isr.close();        } catch (IOException e) {          e.printStackTrace();        }      }      if(is != null){        try {          is.close();        } catch (IOException e) {          // TODO Auto-generated catch block          e.printStackTrace();        }      }            if(osw != null){        try {          osw.close();        } catch (IOException e) {          // TODO Auto-generated catch block          e.printStackTrace();        }      }            if(os != null){        try {          os.close();        } catch (IOException e) {          // TODO Auto-generated catch block          e.printStackTrace();        }      }    }        /**     * 
 
   * 用io读取文件内容 
   * 
     *     * @throws IOException     *       读取过程中发生错误     *     */        /**     * 
 
   * 
   * 
     * @param path     * @param charset     * @throws IOException     *     */    public void read(String path, String charset) throws IOException {      fis = new FileInputStream(path);      isr = new InputStreamReader(fis, charset);      while (fis.available() > 0) {        int length = isr.read(ch);         System.out.println(new String(ch));      }    }          public static void main(String[] args) {      try {        CharsetConvertion cc = new CharsetConvertion();        cc.convertionFile();        cc.convertionString();        cc.close();      } catch (IOException e) {        e.printStackTrace();      }    }  }

方法三:java.nio.Charset

package com.qingshan.nio; 
 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.nio.ByteBuffer; 
import java.nio.CharBuffer; 
import java.nio.channels.FileChannel; 
import java.nio.charset.Charset; 
import java.nio.charset.CharsetDecoder; 
import java.nio.charset.CharsetEncoder; 
 
/** 
 * <pre class="brush:php;toolbar:false"> 
 * 使用nio中的Charset转换字符:整个流程是文件读取-->byte-->解码(正确)-->编码--->byte-->写入文件 
 * 
   * 
   *    * 2012 Qingshan Group 版权所有   * 
   *    *   * @author thetopofqingshan   * @version 1.0.0   * @since JDK 1.5   * @date 2012-4-27   */  public class CharsetConvertion {    private FileInputStream fis;// 文件输入流:读取文件中内容    private FileChannel in;// 文件通道:双向,流从中而过    private FileChannel out;// 文件通道:双向,流从中而过    private FileOutputStream fos;// 文件输出流:向文件中写入内容    private ByteBuffer b = ByteBuffer.allocate(1024 * 3);// 设置缓存区的大小    private Charset inSet;// 解码字符集    private Charset outSet;// 编码字符集    private CharsetDecoder de;// 解码器    private CharsetEncoder en;// 编码器    private CharBuffer convertion;// 中间的字符数据    private ByteBuffer temp = ByteBuffer.allocate(1024 * 3);// 设置缓存区的大小:临时    private byte[] by = new byte[1024];    private InputStreamReader isr;    private char[] ch = new char[1024];      /**     * 
 
   * 
   * 
     *     * @param src     * @param dest     * @throws IOException     *     */    public void convertionFile_nio(String src, String dest) throws IOException {      fis = new FileInputStream(src);      in = fis.getChannel();      fos = new FileOutputStream(dest);      out = fos.getChannel();      inSet = Charset.forName("gbk");      outSet = Charset.forName("utf-8");      de = inSet.newDecoder();      en = outSet.newEncoder();      while (fis.available() > 0) {        b.clear();// 清除标记        in.read(b); // 将文件内容读入到缓冲区内:将标记位置从0-b.capacity(),              // 读取完毕标记在0-b.capacity()之间        b.flip();// 调节标记,下次读取从该位置读起        convertion = de.decode(b);// 开始编码          temp.clear();// 清除标记        temp = en.encode(convertion);        b.flip(); // 将标记移到缓冲区的开始,并保存其中所有的数据:将标记移到开始0        out.write(temp); // 将缓冲区内的内容写入文件中:从标记处开始取出数据      }    }      /**     * 
 
   * 测试转码是否成功, 指定字符集读取文件 
   * 
     *     * @param src     *      被复制文件全路径     * @param charset 解码字符集     *     * @throws IOException 读取过程中的发生的异常     *     */    public void read(String path, String charset) throws IOException {      fis = new FileInputStream(path);      isr = new InputStreamReader(fis, charset);      while (fis.available() > 0) {        int length = isr.read(ch);        System.out.println(new String(ch));      }    }      /**     * 
 
   * 关闭所有流或通道 
   * 
     *     */    public void close() {      try {        if (in != null) {          in.close();        }      } catch (IOException e) {        e.printStackTrace();      }        try {        if (out != null) {          out.close();        }      } catch (IOException e) {        e.printStackTrace();      }        try {        if (fis != null) {          fis.close();        }      } catch (IOException e) {        e.printStackTrace();      }        try {        if (fos != null) {          fos.close();        }      } catch (IOException e) {        e.printStackTrace();      }    }      public static void main(String[] args) {      CharsetConvertion n = new CharsetConvertion();      try {         n.convertionFile_nio("C:/项目进度跟踪.txt", "C:/nio_write.txt");  //     n.read("C:/nio_write.txt", "utf-8");// 正确        // n.read("C:/nio_write.txt", "gbk");//乱码      } catch (IOException e) {        e.printStackTrace();      } finally {        n.close();      }    }    }

以上是三種方法實作java字元轉碼的實例程式碼總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Java平台是否獨立,如果如何?Java平台是否獨立,如果如何?May 09, 2025 am 12:11 AM

Java是平台獨立的,因為其"一次編寫,到處運行"的設計理念,依賴於Java虛擬機(JVM)和字節碼。 1)Java代碼編譯成字節碼,由JVM解釋或即時編譯在本地運行。 2)需要注意庫依賴、性能差異和環境配置。 3)使用標準庫、跨平台測試和版本管理是確保平台獨立性的最佳實踐。

關於Java平台獨立性的真相:真的那麼簡單嗎?關於Java平台獨立性的真相:真的那麼簡單嗎?May 09, 2025 am 12:10 AM

Java'splatFormIndenceIsnotsimple; itinvolvesComplexities.1)jvmcompatiblemustbebeeniblemustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)

Java平台獨立性:Web應用程序的優勢Java平台獨立性:Web應用程序的優勢May 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM解釋:Java虛擬機的綜合指南JVM解釋:Java虛擬機的綜合指南May 09, 2025 am 12:04 AM

thejvmistheruntimeenvorment forexecutingjavabytecode,Cocucialforjava的“ WriteOnce,RunanyWhere”能力

Java的主要功能:為什麼它仍然是頂級編程語言Java的主要功能:為什麼它仍然是頂級編程語言May 09, 2025 am 12:04 AM

JavaremainsatopchoicefordevelopersduetoitsplatFormentence,對象與方向設計,強度,自動化的MememoryManagement和ComprechensivestAndArdArdArdLibrary

Java平台獨立性:這對開發人員意味著什麼?Java平台獨立性:這對開發人員意味著什麼?May 08, 2025 am 12:27 AM

Java'splatFormIndependecemeansDeveloperScanWriteCeandeCeandOnanyDeviceWithouTrecompOlding.thisAcachivedThroughThroughTheroughThejavavirtualmachine(JVM),WhaterslatesbyTecodeDecodeOdeIntComenthendions,允許univerniverSaliversalComplatibilityAcrossplatss.allospplats.s.howevss.howev

如何為第一次使用設置JVM?如何為第一次使用設置JVM?May 08, 2025 am 12:21 AM

要設置JVM,需按以下步驟進行:1)下載並安裝JDK,2)設置環境變量,3)驗證安裝,4)設置IDE,5)測試運行程序。設置JVM不僅僅是讓其工作,還包括優化內存分配、垃圾收集、性能調優和錯誤處理,以確保最佳運行效果。

如何查看產品的Java平台獨立性?如何查看產品的Java平台獨立性?May 08, 2025 am 12:12 AM

toensurejavaplatFormIntence,lofterTheSeSteps:1)compileAndRunyOpplicationOnmultPlatFormSusiseDifferenToSandjvmversions.2)upureizeci/cdppipipelinelikeinkinslikejenkinsorgithikejenkinsorgithikejenkinsorgithikejenkinsorgithike forautomatecross-plateftestesteftestesting.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具