Java基础-I/O流(文件字节流)
字符串常见的字符底层组成是什么样的?
英文和数字等在任何国家的字符集中都占1个字节 GBK字符中一个中文字符占2个字节 UTF-8编码中一个中文字符占3个字节
注意,编码前的字符集和编码好的字符集要必须一致,否则会出现中文字符乱码,英文和数字在任何国家的编码中都不会乱码(编码都占1个字节)。
public class Test {
public static void main(String[] args) throws UnsupportedEncodingException {
// 1、编码:把文字转换成字节(使用指定的编码)
String name = "abc我爱你中国";
// byte[] bytes = name.getBytes(); // 以当前代码默认字符集进行编码(UTF-8)
byte[] bytes = name.getBytes("GBK"); // 指定编码
System.out.println(bytes.length);
System.out.println(Arrays.toString(bytes));
// 2、解码:把字节转换成对应的中文形式(编码前和编码后的字符集必须一致,否则乱码)
// String rs = new String(bytes); // 默认的UTF-8
String rs = new String(bytes, "GBK"); // 默认的UTF-8
System.out.println(rs);
}
}
97 98 51 -1
读取了几个字节:3 ab3 读取了几个字节:3 abc 读取了几个字节:2 cd -1
// 改进使用循环,每次读取一个字节数组
byte[] buffer = new byte[3];
int len; // 记录每次读取的字节数
while ((len = inputStream.read(buffer)) != -1) {
// 读取多少倒出多少
System.out.print(new String(buffer, 0, len));
}
ab3abccd
读取了多少个字节: 31 文件大小:31 ab3abcd我ff爱ff你d花bb花cd
public class OutputStreamDemo {
public static void main(String[] args) throws IOException {
// 1、创建一个文件字节输出流管道与目标文件接通
OutputStream os = new FileOutputStream("D:\ideaProject\reflectDemo\src\data03.txt", true); // 先清空之前的数据,写新数据进入
// 2、写数据出去
// public void write(int a):写一个字节出去
os.write(a);
os.write(98);
os.write("
".getBytes()); // 换行
// os.write(徐);
// public void write(byte[] buffer):写一个字节数组出去
byte[] buffer = {a, 97, 98, 99};
os.write(buffer);
os.write("
".getBytes()); // 换行
byte[] buffer2 = "我是中国人".getBytes();
os.write(buffer2);
os.write("
".getBytes()); // 换行
// 写一个字节数组的一部分出去
byte[] buffer3 = {a, 97, 98, 99};
os.write(buffer3, 0, 3);
os.write("
".getBytes()); // 换行
// os.flush(); // 写数据必须刷新数据,可以继续使用流
os.close(); // 释放资源,包含了刷新的,关闭后流不能使用了
}
}
ab aabc 我是中国人 aab
