---
title: "Java中需要编码的场景"
author: "莫欺少年穷Java"
date: "2016-04-17T13:44:05Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2016-04-17T13:44:05Z"
id: 2291899
url: "https://hejiawangjava.iteye.com/blog/2291899"
---

一般涉及编码的地方包括IO操作和内存操作，ＩＯ操作又分为磁盘ＩＯ和网络IO，首先看磁盘IO是如何通过代码实现编码场景的

```
String file = "/home/wang/test.txt";
		String charset = "UTF-8";
		
		//写字符转换成字节流
		FileOutputStream outputStream = new FileOutputStream(file);
		OutputStreamWriter writer = new OutputStreamWriter(outputStream, charset);
		try{
			writer.write("保存的中文字符");
		}finally{
			writer.close();
		}
		
		//读取字节转换成字符
		FileInputStream inputStream = new FileInputStream(file);
		InputStreamReader reader = new InputStreamReader(inputStream, charset);
		StringBuffer buffer = new StringBuffer();
		char[] buf = new char[64];
		int count = 0;
		try{
			while( (count = reader.read(buf)) != -1 ){
				buffer.append(buf, 0, count);
			}
		}finally{
			reader.close();
		}
```

 

        IO编码的场景还有网络IO，其中有URL的编解码、HTTP Header的编解码、POST编码的编解码、HTTP BODY的编解码、还有在JS中的编码问题，都是javaweb中涉及的编解码问题了，就不细说了。

        下面说说在内存操作中的编码，

         1、String类提供的编码转换方法

```
                String s = "中文字符串";
		//String类提供的转换方法
		byte[] b = s.getBytes("UTF-8");
		String n = new String(b, "UTF-8");
```

         2、Charset类提供的编码转换方法

```
                String s = "中文字符串";
		//Charset类提供的encode(字符到字节)和decode(字节到字符)
		Charset charset = Charset.forName("UTF-8");
		ByteBuffer byteBuffer = charset.encode(s);
		CharBuffer charBuffer = charset.decode(byteBuffer);
```

          3、还有一个ByteBuffer类提供的编码转换方法，

```
 		ByteBuffer heapByteBuffer = ByteBuffer.allocate(1024);
		ByteBuffer bytebuffer = heapByteBuffer.putChar(c)
```

 

        如果在应用程序中不注意指定字符编码，则在中文环境中会使用操作系统默认的编码，这样在换平台的时候容易出现乱码的情况。