java 中,char 数组转换成 byte数组(急,在线等)
发布网友
发布时间:2022-04-21 14:33
我来回答
共5个回答
热心网友
时间:2023-06-22 07:23
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();//返回字符数组
}
}
热心网友
时间:2023-06-22 07:23
你看这样能达到你的目的吗
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
热心网友
时间:2023-06-22 07:24
char []acCharArray = new char[...];
... ...
byte [] abByteArray = String.valueOf(acCharArray).getBytes();
... ...
热心网友
时间:2023-06-22 07:24
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] + " ");
}
}
热心网友
时间:2023-06-22 07:25
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();
}
}