java如何输出中文字符

560
2023/9/2 17:56:44
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,可以使用字符流和字节流来输出中文字符。

  1. 使用字符流输出中文字符:
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8"));
writer.write("你好,世界!");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
  1. 使用字节流输出中文字符:
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
OutputStream outputStream = new FileOutputStream("output.txt");
outputStream.write("你好,世界!".getBytes("UTF-8"));
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

请注意,为了正确地输出中文字符,需要指定正确的字符编码,例如UTF-8。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Java getAbsolutePath()获取绝对路径和相对路径