java将字节数组转换成一个字符串
首先我们有一个字节数组,假设我们有一个文件java.txt,里面有2行数据
你好我爱你
使用字节流将文件内容读取到byte数组中,
public class InputStream1 { public static void main(String[] args) throws IOException { FileInputStream fileInputStream = new FileInputStream(new File("G:\javaStudy\java.txt")); byte[] bytes = new byte[100];//如果数组长度不够,读取数组长度的数据,指针移动,可以接着读 int read1 = fileInputStream.read(bytes); System.out.println(read1); System.out.println(new String(bytes)); fileInputStream.close(); }}我们得到的数组是字节数组,现在我们想让字节数组变成字符串,你好和我爱你,那么我们只需要将使用String 的构造方法String(byte[] bytes),返回的是一个新的String,会对我们的byte数组进行解码。