一:IO流分类
1)按流向分:输入流和输出流
2)按数据类型:字节流:可以是一切文件,如纯文本、图片、音乐、视频等
字符流:只能是纯文本文件
3)按功能分:节点:包裹源头
处理:增强功能,提供性能
二:字节流(重点)、字符流与文件
1).字节流:输入流:InputStream read(byte[] b) read(byte[] b, int off, int len)
close()
如果是文件操作实现类就是FileInputStream,其他操作换用其他实现类就是了。输出流:OutputStream
write(byte[] b)write(byte[] b, int off, int len) close() flush()
如果是文件操作实现类就是FileOutputStream,其他操作换用其他实现类就是了。2)字符流:输入流:Reader
read(char[] cbuf)read(char[] cbuf, int off, int len) close()
如果是文件操作实现类就是FileReader,其他操作换用其他实现类就是了。输出流:Writer
write(char[] cbuf)write(char[] cbuf, int off, int len) close() flush()
如果是文件操作实现类就是FileWriter,其他操作换用其他实现类就是了。
三:操作流程:
1)建立联系
2)选择流
3)操作
4)释放资源
四:读取文件内容:
public static void main(String[] args) {
// 1.建立联系
File src = new File("F:/1.txt");
// 2.选择流
FileInputStream input = null;// 提升作用域
try {
// 3.操作
input = new FileInputStream(src);
byte[] data = new byte[100];// 建立缓冲数组,数组长度可变
int len = 0;// 读出的实际长度
while ((len = input.read(data)) != -1) {// 不断读取文件内容
String info = new String(data, 0, len);// 字节数组转换成字符串
System.out.println(info);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取文件失败");
} finally {
// 4.释放资源
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("关闭输入流失败");
}
}
}
}
五:往文件中写入内容:
public static void main(String[] args) {
// 1.建立联系
File src = new File("F:/1.txt");
// 2.选择流
FileOutputStream out = null;// 提升作用域
try {
out = new FileOutputStream(src, true);// 为true时表示衔接到文件中,为false或者没有时表示覆盖源文件内容
// 3.操作
String str = "I must study hard\r\n";// \r\n相当于Enter键-->换行符
byte[] data = str.getBytes();// 将字符串转换成字节数组
out.write(data);
out.flush();// 强制冲刷出去
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件未找到");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件写入异常");
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件输出流关闭失败");
}
}
}
}

被折叠的 条评论
为什么被折叠?



