1、常用io流概述
Java的io流按功能分,分为输入流和输出流,按处理类型分,分为字节流和字符流。
-
常用字节流:
-
常用字符流:
2、字节流案例
字节输入流:
public class InputStream {
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\last\\Desktop\\代码资料\\filetxt\\a.txt");
//1、创建输入流对象
FileInputStream fis = new FileInputStream(file);
int b;
//2、字节流输入流读取文件并输出
while((b=fis.read())!=-1){
System.out.print(b+" ");
}
//3、关闭输入流
fis.close();
}
}
txt文件里的文字:
控制台输出:
为什么输出不是文字而是数字,因为字符在底层存储的时候就是存储的数值。即字符对应的ASCII码。
字节输出流:
public class OutputStream {
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\last\\Desktop\\代码资料\\filetxt\\a.txt");
//1、创建输出流对象
FileOutputStream fos = new FileOutputStream(file);
//2、准备数据,并转换为字节或数组类型
String msg="\n野火烧不尽,\n春风吹又生";
byte[] bytes = msg.getBytes();
//2、往文件里面写入数据
fos.write(bytes);
//4、关闭输出流
fos.close();
}
}
运行程序把文字写入到了txt文本中
ps:new FileOutputStream(file)是如果没有这个文件,会自己创建一个,而FileInputStream不会自己创建,会直接报错。