21xrx.com
2025-04-27 11:26:12 Sunday
文章检索 我的文章 写文章
Java编码转换代码-将文本从一种编码格式转换为另一种
2023-06-15 09:40:30 深夜i     27     0
Java编程 编码转换 UTF-8

在Java编程中,经常需要对不同编码格式的文本进行转换。Java中提供了一些API可以用来进行编码转换。下面介绍一些常用的编码转换代码:

1. 将字符串从UTF-8编码转换为GBK编码

String utf8Str = "UTF-8编码的字符串";
byte[] utf8Bytes = utf8Str.getBytes("UTF-8");
String gbkStr = new String(utf8Bytes, "GBK");
System.out.println("转换后的GBK编码字符串:" + gbkStr);

2. 将字符串从GBK编码转换为UTF-8编码

String gbkStr = "GBK编码的字符串";
byte[] gbkBytes = gbkStr.getBytes("GBK");
String utf8Str = new String(gbkBytes, "UTF-8");
System.out.println("转换后的UTF-8编码字符串:" + utf8Str);

3. 将文件从UTF-8编码转换为GBK编码

FileInputStream fis = new FileInputStream("utf8File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
FileOutputStream fos = new FileOutputStream("gbkFile.txt");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, "GBK"));
String line;
while ((line = br.readLine()) != null) {
  bw.write(line);
  bw.newLine();
}
br.close();
bw.close();

通过以上的代码,我们可以将文本从一种编码格式转换为另一种编码格式。在Java编程中,编码转换是一个很常见的操作,掌握好这些API可以提高我们的编程效率。

  
  

评论区