1.基本概念
1.1 什么是IO流
I:input(输入)
O:output(输出)
流:stream
IO流是存储和读取数据的解决方案。程序控制流。
1.2 IO流的作用
读取数据(本地读到网络,网络读到本地)
1.3 IO流类别
1.3.1 根据流向区别
输入流:InputStream,本地数据读到程序中
输出流:OutputStream,程序数据读到本地
1.3.2 根据处理数据的方式
字节流:操作所有类型文件
字符流:只能操作纯文本文件(windows记事本可以正常打开不乱码)
2.文件输出流(FileOutputStream)
2.1 步骤
2.1.1 创建对象
创建文件输出流对象,参数可以是绝对路径或者文件。
当前文件存在,就清空再写入。
当前文件不存在,就新建。
2.1.2 写出数据
writer方法参数是整数,实际是整数在ASCII对应的字符。
2.1.3 释放资源
每次写完之后需要释放资源。
2.2 一次输出一个字符
public static void main(String[] args) throws IOException {
//1.创建对象
FileOutputStream fop = new FileOutputStream("D:\\ideaProject\\IoPractice\\src\\main\\java\\cn\\file\\output\\demo01.txt");
//2.写出数据
fop.write(98);
//3.关闭流
fop.close();
}
2.3 一次输出一个字符数组
public static void main(String[] args) throws IOException {
//1.创建对象
FileOutputStream fop = new FileOutputStream("D:\\ideaProject\\IoPractice\\src\\main\\java\\cn\\file\\output\\demo02.txt");
//2.写出数据
byte[] b={97,98,99,100};
fop.write(b);
//3.关闭流
fop.close();
}
2.3 一次输出一个数组,可控制从哪个索引开始,输入几个字符
public static void main(String[] args) throws IOException {
//1.创建对象
FileOutputStream fop = new FileOutputStream("D:\\ideaProject\\IoPractice\\src\\main\\java\\cn\\file\\output\\demo03.txt");
//2.写出数据
byte[] b={97,98,99,100};
fop.write(b,0,3);
//3.关闭流
fop.close();
}
2.4 续写
public static void main(String[] args) throws IOException {
//1.创建对象
FileOutputStream fop = new FileOutputStream("D:\\ideaProject\\IoPractice\\src\\main\\java\\cn\\file\\output\\demo04.txt",true);
//2.写出数据
byte[] b={97,98,99,100};
fop.write(b,0,3);
//3.关闭流
fop.close();
}
2.5 换行
public static void main(String[] args) throws IOException {
//1.创建对象
FileOutputStream fop = new FileOutputStream("D:\\ideaProject\\IoPractice\\src\\main\\java\\cn\\file\\output\\demo05.txt");
//2.写出数据
String s1= "123wer345";
byte[] bytes1 = s1.getBytes();
fop.write(bytes1);
String s2 ="\r\n";
byte[] bytes2 = s2.getBytes();
fop.write(bytes2);
fop.write(bytes1);
//3.关闭流
fop.close();
}