一、文本的写入
String name="张三你好";
byte[] bytes = name.getBytes("UTF-8");
// 文件路径
File file = new File("explame.txt");
OutputStream outputStream = new FileOutputStream(file);
outputStream.write(bytes);
outputStream.close();

二、文本的输出
// 用于接受数据的缓冲区
byte[] buffer = new byte[1000];
// 文件放在根目录下
File file = new File("explame.txt");
// 从文件中读取数据,放到缓冲区中
InputStream inputStream = new FileInputStream(file);
int n = inputStream.read(buffer, 0, 1000);
inputStream.close();
System.out.println("读取了"+n+"个字节");
// 将前n个字节转成字符串
String str= new String(buffer,0,n,"UTF-8");
System.out.println("内容"+str);

中文乱码出现的本质原因:是解码方式不正确导致,在一段文本文字中,编码使用GBK进行编码,而你使用UTF8进行解码,解码和编码方式不一致,则会出现乱码问题
三、byte[] 和inputStream 相互转化
1:byte[]转换为InputStream
InputStream sbs = new ByteArrayInputStream(byte[] buf);
2:InputStream转换为InputStreambyte[]
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in_b = swapStream.toByteArray(); //in_b为转换之后的结果
代码:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class ByteToInputStream {
public static final InputStream byte2Input(byte[] buf) {
return new ByteArrayInputStream(buf);
}
public static final byte[] input2byte(InputStream inStream)
throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
}
网友评论