java IO流笔记 字节流
/** * io流注意事项 * 1,idea默认编码是UTF8,有些windows系统的默认编码是ANSI,有些是utf8 * 2,在简体中文操系统中,ANSI编码代表GBK编码 * 3,一个中文字在utf8编码下占用3个字节,在GBK编码下占用两个字节 * 4,读写编码需要一致,否则会乱码 */ /** * 字节输出流【OutputStream】常用方法 * 概述:java.io.OutputStream这个抽象类是所有字节输出流的父类,以字节为单位输出数据 * 常用方法: * write方法,写入,会覆盖原文件内容 * close方法 */
public class Test {
public static void main(String[] args) throws IOException {
File file = new File("IO流\\aaa\\1.txt");
//如果文件不存在,它会自动创建一个空文件,但是文件夹和文件都不存在则会报异常
FileOutputStream fileOutputStream = new FileOutputStream(file);
//方式二
FileOutputStream fileOutputStream2 = new FileOutputStream("IO流\\aaa\\1.txt");
String str = "6666666werwer张三";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
//写入数据
fileOutputStream2.write(bytes);
//关闭流
fileOutputStream2.close();
}
}
/**
* 字节输入流【InputStream】
* 概述:java.io.InputStream这个抽象类是字节输入流的父类。可以用来读取字节数据到内存中
* 常用方法:
* read
* close
*/
public class Test2 {
/**
* 字节输入流
*/
public static void main(String[] args) throws IOException {
File file = new File("IO流\\aaa\\2.txt");
FileInputStream fileInputStream = new FileInputStream(file);
//方法一
/*int i =0;
while ((i = fileInputStream.read())!=-1){
System.out.println((char)i);
}*/
//方法二
/*int length = (int)file.length();
byte[] bytes = new byte[length];*/
byte[] bytes = new byte[8192];
//fileInputStream.read(bytes)返回读到的字节个数
int j = 0;
while ((j=fileInputStream.read(bytes))!=-1){
System.out.println(new String(bytes,0,j));
}
fileInputStream.close();
}
}

浙公网安备 33010602011771号