IO流
Posted Stupefy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IO流相关的知识,希望对你有一定的参考价值。
IO流
按方向:
-
输入流:将存储设备中的内容读入到内存中
-
输出流:将内存中的内容写入到存储设备中
按单位:
-
字节流:以字节为单位,可以读写所有数据
-
字符流:以字符为单位,只能读写文本数据
按功能:
-
节点流:具有实际传输数据的读写功能
-
过滤流:在节点流的基础之上增强功能
字节流:
字节流的父类:
-
InputStream:字节输入流
-
OutputStream:字节输出流
文件字节流:
-
FileInputStream:
-
public int read(byte[] b)//从流中读取多个字节,将读到的内容存入b数组,返回实际读到的字节数;如果达到文件的尾部,则返回-1
-
package com.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
//FileInputStream文件字节输入流的使用
public class FileInputStreamDemo
public static void main(String[] args) throws Exception
//创建FileInputStream
FileInputStream fileInputStream = new FileInputStream("/Users/zhaoliang/IdeaProjects/aaa.txt");
//读取文件
// System.out.println("=====================单个字节读取=====================");
// int data = 0;
// while ((data=fileInputStream.read())!=-1)
// System.out.print((char) data);
//
System.out.println("=====================一次读取多个字节=====================");
byte[] bytes = new byte[1024];
int count = 0;
while ((count = fileInputStream.read(bytes))!=-1)
System.out.println(new String(bytes,0,count));
//关闭
fileInputStream.close();
System.out.println("执行完毕");
-
FileOutputStream:
-
public void write(byte[] b)//一次写多个字节,将b数组中所有字节,写入输出流
-
package com.io;
import java.io.FileOutputStream;
//FileOutputStream文件字节输出流
public class FileOutputStreamDemo
public static void main(String[] args) throws Exception
//创建文件字节输出流对象
FileOutputStream fileOutputStream = new FileOutputStream("/Users/zhaoliang/IdeaProjects/bbb.txt",true);
//写入文件
fileOutputStream.write(97);
fileOutputStream.write(\'b\');
fileOutputStream.write(\'c\');
String string = "helloword";
fileOutputStream.write(string.getBytes());
//关闭
fileOutputStream.close();
System.out.println("执行完毕");
字节缓冲流
缓冲流(BufferedInputStream/BufferedOutputStream)
-
提高io效率,减少访问磁盘的次数
-
数据存储在缓冲区中,flush是将缓存区的内容写入到文件中,也可以直接close
BufferedInputStream:
package com.io;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
//使用字节缓冲流读取
public class BufferedInputStreamDemo
public static void main(String[] args) throws Exception
//创建BufferedInputStream
FileInputStream fileInputStream = new FileInputStream("/Users/zhaoliang/IdeaProjects/aaa.txt");
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
//读取
// int data = 0;
// while ((data=bufferedInputStream.read())!=-1)
// System.out.print((char) data);
//
//自己创建的缓冲流
byte[] bytes = new byte[1024];
int count = 0;
while ((count=bufferedInputStream.read(bytes))!=-1)
System.out.print(new String(bytes,0,count));
//关闭
bufferedInputStream.close();
BufferedOutputStream:
package com.io;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
//使用字节缓冲流写入文件
public class BufferedOutputStreamDemo
public static void main(String[] args) throws Exception
//创建字节输出缓冲流
FileOutputStream fileOutputStream = new FileOutputStream("/Users/zhaoliang/IdeaProjects/buffer.txt");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
//写入
for (int i = 0; i < 10; i++)
bufferedOutputStream.write("helloword\\n".getBytes());//先写入缓冲区
bufferedOutputStream.flush();//刷新到硬盘
//关闭(内部调用flush方法)
bufferedOutputStream.close();
System.out.println("执行完毕");
对象流
对象流ObjectOutputStream/ObjectInputStream
-
增强了缓冲区的功能
-
增强了读写8种基本数据类型的字符串的功能
-
增强了读写对象的功能
-
readObject()从流中读取一个对象
-
writeObject(Object obj)向流中写入一个对象
-
使用流传输对象的过程称为序列化、反序列化
package com.io;
import java.io.Serializable;
public class Student implements Serializable
private String name;
private transient int age;
public Student(String name, int age)
this.name = name;
this.age = age;
public String getName()
return name;
public void setName(String name)
this.name = name;
public int getAge()
return age;
public void setAge(int age)
this.age = age;
@Override
public String toString()
return "Student" +
"name=\'" + name + \'\\\'\' +
", age=" + age +
\'\';
序列化:
package com.io;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
//使用ObjectOutputStream实现对象的序列化
//序列化类必须要实现Serializable接口
//序列化类中对象的属性要求实现Serializable接口
//使用transient(瞬间的)修饰属性,这个属性就不能序列化,在内存中
//静态属性不能序列化public static String country = "中国";
//序列化多个对象:可以借助集合来实现
public class ObjectOutputStreamDemo
public static void main(String[] args) throws Exception
//创建对象流
FileOutputStream fileOutputStream = new FileOutputStream("/Users/zhaoliang/IdeaProjects/stu.bin");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
//序列化(写入)
Student s1 = new Student("肥肥", 20);
Student s2 = new Student("里斯", 22);
ArrayList<Student> arrayList = new ArrayList<>();
arrayList.add(s1);
arrayList.add(s2);
objectOutputStream.writeObject(arrayList);
//关闭
objectOutputStream.close();
System.out.println("序列化完毕");
反序列化
package com.io;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
//使用ObjectInputStream实现反序列化(读取重构成对象)
public class ObjectInputStreamDemo
public static void main(String[] args) throws Exception
//创建对象流
FileInputStream fileInputStream = new FileInputStream("/Users/zhaoliang/IdeaProjects/stu.bin");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
//反序列化(读取)
// Student s = (Student) objectInputStream.readObject();
// Student s2 = (Student) objectInputStream.readObject();
ArrayList<Student> list = (ArrayList<Student>) objectInputStream.readObject();
// System.out.println(s.toString());
// System.out.println(s2.toString());
System.out.println(list.toString());
//关闭
objectInputStream.close();
System.out.println("反序列化完毕");
字符编码
-
IS0-8859-1收录除ASCII外,还包括西欧、希腊语、泰语、阿拉伯语、希伯来语对应的文字符号。
-
UTF-8针对Unicode码表的可变长度字符编码
-
GB2312简体中文
-
GBK简体中文、扩充
-
BIG5 台湾,繁体中文
字符流
-
Reader:字符输入流
-
public int read()
-
public int read (char[] c)
-
public int read (char[] b, int off, int len)
-
-
Writer:字符输出流
-
public void write (int n)
-
public void write (String str)
-
public void write (char[] c)
-
文件字符流
FileReader:
-
public int read (char[] c)//从流中读取多个字符,将读到内容存入c数组,返回实际读到的字符数;如果达到文件的尾部,则返回-1。
package com.io;
import java.io.FileInputStream;
import java.io.FileReader;
public class FileReaderDemo
public static void main(String[] args) throws Exception
//创建FileInputStream对象
FileReader fileReader = new FileReader("/Users/zhaoliang/IdeaProjects/hello.txt");
//读取
// int data = 0;
// while ((data=fileReader.read())!=-1)
// System.out.print((char) data);
//
char[] buf = new char[1024];
int count = 0;
while ((count = fileReader.read(buf))!=-1)
System.out.println(new String(buf,0,count));
//关闭
fileReader.close();
FileWriter:
-
public void write (String str) //一次写多个字符,将b数组中所有字符,写入输出流
package com.io;
import java.io.FileWriter;
public class FileWriterDemo
public static void main(String[] args) throws Exception
//创建FileWrite对象
FileWriter fileWriter = new FileWriter("/Users/zhaoliang/IdeaProjects/word.txt");
//写入
for (int i = 0; i < 10; i++)
fileWriter.write("\\njava是世界上最好的语言");
fileWriter.flush();
//关闭
fileWriter.close();
文件复制
复制一张图片
package com.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
//使用文件字节流实现文件的复制
public class CopyDemo01
public static void main(String[] args) throws Exception
//创建文件字节输入流
FileInputStream fileInputStream = new FileInputStream("/Users/zhaoliang/IdeaProjects/1.png");
//创建文件字节输出流
FileOutputStream fileOutputStream = new FileOutputStream("/Users/zhaoliang/IdeaProjects/2.png");
//一边读一边写
//创建缓冲区
byte[] buf = new byte[1024];
int count = 0;
while ((count=fileInputStream.read(buf))!=-1)
fileOutputStream.write(buf,0,count);
//关闭
fileInputStream.close();
fileOutputStream.close();
System.out.println("执行完毕");
复制文本文件
package com.io;
import java.io.FileReader;
import java.io.FileWriter;
//使用FileReader和FileWriter复制文本文件,不能复制图片和二进制文件
//使用字节流可以复制任何文件
public class CopyDemo02
public static void main(String[] args) throws Exception
//创建FileReader和FileWriter对象
FileReader fileReader = new FileReader("/Users/zhaoliang/IdeaProjects/word.txt");
FileWriter fileWriter = new FileWriter("/Users/zhaoliang/IdeaProjects/helloword.txt");
//读写
char[] buf = new char[1024];
int count = 0;
while ((count=fileReader.read(buf))!=-1)
fileWriter.write(buf,0,count);
fileWriter.flush();
fileWriter.close();
fileReader.close();
System.out.println("执行完毕");
字符缓冲流
缓冲流:BufferedReader/BufferedWriter
-
高效读写
-
支持输入换行符
-
可一次写一行、读一行
BufferedReader
package com.io;
import java.io.BufferedReader;
import java.io.FileReader;
//使用字符缓冲流BufferedReader
public class BufferedReaderDemo
public static void main(String[] args) throws Exception
//创建BufferedReader对象
FileReader fileReader = new FileReader("/Users/zhaoliang/IdeaProjects/word.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
//读取
//自创缓冲区
// char[] buf = new char[1024];
// int count = 0;
// while ((count=fileReader.read(buf))!=-1)
// System.out.println(new String(buf,0,count));
//
//一行一行的读
String line = null;
while ((line=bufferedReader.readLine())!=null)
System.out.println(line);
//关闭
fileReader.close();
System.out.println("执行完毕");
BufferedWriter
package com.io;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class BufferedWriterDemo
public static void main(String[] args) throws Exception
//创建BufferedWriter对象
FileWriter fileWriter = new FileWriter("/Users/zhaoliang/IdeaProjects/io流/buffer.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
//写入
for (int i = 0; i < 10; i++)
bufferedWriter.write("猪猪侠gg棒");
bufferedWriter.newLine();
bufferedWriter.flush();
//关闭
bufferedWriter.close();
System.out.println("执行完毕");
打印流
PrintWriter
-
封装了print()/println()方法,支持写入后换行
-
支持数据原样打印
package com.io;
import java.io.PrintWriter;
public class PrintWriterDemo
public static void main(String[] args) throws Exception
//创建打印流
PrintWriter printWriter = new PrintWriter("/Users/zhaoliang/IdeaProjects/io流/print.txt");
//打印
printWriter.println(97);
printWriter.println(true);
printWriter.println(3.14);
printWriter.println(\'a\');
//关闭
printWriter.close();
转换流
桥转换流:InputStreamReader/OutputStreamWriter
-
可将字节流转换为字符流
-
可设置字符的编码方式
InputStreamReader
package com.io;
import java.io.FileInputStream;
import java.io.InputStreamReader;
//使用InputStreamReader读取文件,指定使用的编码
public class InputStreamReaderDemo
public static void main(String[] args) throws Exception
//创建InputStreamReader
FileInputStream fileInputStream = new FileInputStream("/Users/zhaoliang/IdeaProjects/io流/buffer.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
//读取
int data = 0;
while ((data=inputStreamReader.read())!=-1)
System.out.print((char) data);
//关闭
inputStreamReader.close();
System.out.println("执行完毕");
OutputStreamWriter
package com.io;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class OutputStreamWriterDemo
public static void main(String[] args) throws Exception
//创建OutputStreamWriter对象
OutputStream fileOutputStream = new FileOutputStream("/Users/zhaoliang/IdeaProjects/io流/a.txt");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"gbk");
//写入
for (int i = 0; i < 10; i++)
outputStreamWriter.write("肥肥天\\n");
outputStreamWriter.flush();
//关闭
outputStreamWriter.close();
System.out.println("执行完毕");
File类
概念:代表物理盘符中的一个文件或者文件夹。
方法:
-
createNewFile() //创建一个新文件
-
mkdir() //创建一个新目录
-
delete () //删除文件或空目录
-
exists() //判断File对象所对象所代表的对象是否存在
-
getAbsolutePath() //获取文件的绝对路径
-
getName () //取得名字
-
getParent () //获取文件/目录所在的目录
-
isDirectory() //是否是目录
-
isFile() //是否是文件
-
length() //获得文件的长度
-
listFiles() //列出目录中的所有内容
-
renameTo() / /修改文件名为
package com.io;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.IOException;
import java.util.Date;
/**File类的使用
* 分隔符
* 文件操作
* 文件夹操作
*/
public class FileDemo
public static void main(String[] args) throws Exception
//separator();
//fileOpe();
directoryOpe();
//分隔符
public static void separator() throws Exception
System.out.println("路径分隔符" + File.pathSeparator);
System.out.println("名称分隔符" + File.separator);
//文件操作
public static void fileOpe() throws Exception
//创建文件
File file = new File("/Users/zhaoliang/IdeaProjects/io流/b.txt");
//System.out.println(file.toString());
if (!file.exists())
boolean b = file.createNewFile();
System.out.println("创建结果" + b);
//删除文件
//直接删除
//System.out.println("删除结果" + file.delete());
//使用jvm推出时删除
// file.deleteOnExit();
// Thread.sleep(5000);
//获取文件信息
System.out.println("获取文件的绝对路径:" + file.getAbsolutePath());
System.out.println("获取路径:" + file.getPath());
System.out.println("获取文件名称:" + file.getName());
System.out.println("获取父目录:" + file.getParent());
System.out.println("获取文件长度:" + file.length());
System.out.println("获取文件创建时间:" + new Date(file.lastModified()).toLocaleString());
//判断
System.out.println("是否可写:" + file.canWrite());
System.out.println("是否是文件:" + file.isFile());
System.out.println("文件是否隐藏:" + file.isHidden());
//文件夹操作
public static void directoryOpe() throws Exception
//创建文件夹
File dir = new File("/Users/zhaoliang/IdeaProjects/io流/aaa/bbb/ccc");
System.out.println(dir.toString());
if (!dir.exists())
//dir.mkdir();//只能创建单级目录
//dir.mkdirs();//可以创建多级目录
System.out.println("创建结果:" + dir.mkdirs());
//删除文件夹
//直接删除
//System.out.println("删除结果:" + dir.delete());//只删除最底层目录,而且只删除空目录
//使用jvm删除
// dir.deleteOnExit();
// Thread.sleep(5000);
//获取文件夹信息
System.out.println("获取绝对路径:" + dir.getAbsolutePath());
System.out.println("获取路径:" + dir.getPath());
System.out.println("获取文件夹名称:" + dir.getName());//最内层文件夹名称
System.out.println("获取父目录:" + dir.getParent());
System.out.println("获取创建时间:" + new Date(dir.lastModified()).toLocaleString());
//判断
System.out.println("是否是文件夹:" + dir.isDirectory());
System.out.println("是否是隐藏:" + dir.isHidden());
//遍历文件夹
File dir2 = new File("/Users/zhaoliang/IdeaProjects/io流");
String[] files = dir2.list();
System.out.println("===============================");
for (String s: files)
System.out.println(s);
FileFilter接口
当调用File类中的listFiles()方法时,支持传入FileFilter接口实现类,对获取文件进行过滤,只有满足条件的文件才可出现在listFiles()的返回值
package com.io;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Date;
/**File类的使用
* 分隔符
* 文件操作
* 文件夹操作
*/
public class FileDemo
public static void main(String[] args) throws Exception
//separator();
//fileOpe();
directoryOpe();
//分隔符
public static void separator() throws Exception
System.out.println("路径分隔符" + File.pathSeparator);
System.out.println("名称分隔符" + File.separator);
//文件操作
public static void fileOpe() throws Exception
//创建文件
File file = new File("/Users/zhaoliang/IdeaProjects/io流/b.txt");
//System.out.println(file.toString());
if (!file.exists())
boolean b = file.createNewFile();
System.out.println("创建结果" + b);
//遍历文件夹
File dir2 = new File("/Users/zhaoliang/IdeaProjects/io流");
String[] files = dir2.list();
System.out.println("===============================");
for (String s: files)
System.out.println(s);
System.out.println("================FileFilter接口的使用=================");
File[] files1 = dir2.listFiles(new FileFilter()
@Override
public boolean accept(File pathname)
if (pathname.getName().endsWith(".png"))
return true;
return false;
);
for (File file: files1)
System.out.println(file.getName());
案例
package com.io;
import java.io.File;
/**
* 案例1:
* 递归遍历文件夹
* 案例2:
* 递归删除文件夹
*/
public class listDemo
public static void main(String[] args)
listDir(new File("/Users/zhaoliang/IdeaProjects/io流"));
deleteDir(new File("/Users/zhaoliang/IdeaProjects/io流/files"));
//递归遍历文件夹
public static void listDir(File dir)
File[] files = dir.listFiles();
System.out.println(dir.getAbsolutePath());
if (files!=null&&files.length>0)
for (File file: files)
if (file.isDirectory())
listDir(file);
else
System.out.println(file.getAbsolutePath());
//递归删除文件夹
public static void deleteDir(File dir)
File[] files = dir.listFiles();
if (files!=null&&files.length>0)
for (File file:files)
if (file.isDirectory())
deleteDir(file);
else
//删除文件
System.out.println(file.getAbsolutePath() + "删除" + file.delete());
System.out.println(dir.getAbsolutePath() + "删除" + dir.delete());
总结:
流的概念:
-
内存与存储设备之间传输数据的通道
流的分类:
-
输入流、输出流、字节流、字符流、节点流、过滤流
序列化、反序列化:
-
将对象通过流写入到文件,或将对象通过流读取到内存,必须实现Serializable接口
File对象:
-
代表物理盘符中的一个文件或者文件夹
以上是关于IO流的主要内容,如果未能解决你的问题,请参考以下文章