java 中,char 数组转换成 byte数组(急,在线等)

如题~~~
具体实现例子,谢谢~

package com.example.lib;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.*;
import java.nio.charset.Charset;

public class MyClass {
public static void main(String[] args) throws IOException {
FileInputStream fs; //定义流对象变量
fs = new FileInputStream("/Users/mac/AndroidStudioProjects/MyApplication/lib/src/main/java/com/example/lib/mytext.txt");
byte[] bytes = new byte[fs.available()]; //定义接收数据的字节数组,并用流对象初始化数组大小
fs.read(bytes); //装载数据
char[] w = getChars(bytes);//将字节数组转化为字符数组,注意数组末尾会有空字符
String s = new String(w); //利用字符串构造函数来构造字符串,
System.out.println("结果为:"+s.trim());输出时,去掉末尾空格字符
}

private static byte[] getBytes (char[] chars) {
Charset cs = Charset.forName ("UTF-8");//设定字符集编码代号
CharBuffer cb = CharBuffer.allocate (chars.length);//按照字符数组长度进行分配空间
cb.put (chars); //装载数据
cb.flip (); //指针复位
//按照编码规则进行编码
ByteBuffer bb = cs.encode (cb);
return bb.array();
}

private static char[] getChars (byte[] bytes) {
Charset cs = Charset.forName ("UTF-8");//指定字符集编码
ByteBuffer bb = ByteBuffer.allocate (bytes.length);
bb.put (bytes);//装载数据
bb.flip ();//调整回指针为0
CharBuffer cb = cs.decode (bb);//按照指定字符集进行解码
return cb.array();//返回字符数组
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-09-10
你看这样能达到你的目的吗
char[] ch = new char [] {'a','b'};
byte [] by = new byte[ch.length];
for(int i= 0; i<ch.length ; ++i){
by[i] = (byte)ch[i];
System.out.println(by[i]);
}
输出的是 97 98
第2个回答  2010-09-08
char []acCharArray = new char[...];

... ...

byte [] abByteArray = String.valueOf(acCharArray).getBytes();

... ...
第3个回答  2010-09-08
public static void main(String[] args) {
char[] c = new char[]{'1','2','3','+'};
String str = new String(c);
byte[] b = str.getBytes();
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
}
第4个回答  2010-09-08
class t
{
public static void main(String[] args){
char[] c = new char[]{'a','b','c','d','e','f','g'};
String s = new String(c);
byte[] b = s.getBytes();
}
}