IO流
File类的使用
File类
- File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
- File类声明在java.io包下
- File 能新建、删除、重命名文件和目录,但 File 不能访问文件内容本身。 如果需要访问文件内容本身,则需要使用输入/输出流。
- 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点"
常用构造器
绝对路径:是一个固定的路径,从盘符开始
相对路径:是相对于某个位置开始
- public File(String pathname)
- 以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果 pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。
File file1 = new File("hello.txt");//相对于当前module
File file2 = new File("D:\\IO\\hi.txt");
- public File(String parent,String child)
- 以parent为父路径,child为子路径创建File对象。
File file = new File("D:\\IO","Java");
- public File(File parent,String child)
- 根据一个父File对象和子文件路径创建File对象
File file = new File("D:\\IO\\hi.txt");
File file1 = new File(file,"hi.txt");
路径分隔符
路径中的每级目录之间用一个路径分隔符隔开。
路径分隔符和系统有关
windows和DOS系统默认使用“\”来表示
UNIX和URL使用“/”来表示
Java程序支持跨平台运行,File类提供了一个常量public static final String separator。可根据操作系统,动态的提供分隔符。
File file = new File("d:" + File.separator + "IO" + File.separator + "info.txt");
常用方法
File类的获取功能
- public String getAbsolutePath():获取绝对路径
- public String getPath() :获取路径
- public String getName() :获取名称
- public String getParent():获取上层文件目录路径。若无,返回null
- public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
- public long lastModified() :获取最后一次的修改时间,毫秒值
@Test
public void test(){
File file1 = new File("hello.txt");
File file2 = new File("D:\\IO\\hi.txt");
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getPath());
System.out.println(file1.getName());
System.out.println(file1.getParent());
System.out.println(file1.length());
System.out.println(new Date(file1.lastModified()));
System.out.println();
System.out.println(file2.getAbsolutePath());
System.out.println(file2.getPath());
System.out.println(file2.getName());
System.out.println(file2.getParent());
System.out.println(file2.length());
System.out.println(file2.lastModified());
}
- public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
- public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
@Test
public void test3(){
File file = new File("D:\\IO");
String[] list = file.list();
for(String s : list){
System.out.println(s);
}
System.out.println();
File[] files = file.listFiles();
for(File f : files){
System.out.println(f);
}
File类的重命名功能
- public boolean renameTo(File dest):把文件重命名为指定的文件路径
//以file1.renameTo(file2)为例
// 要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在
@Test
public void test4(){
File file1 = new File("hello.txt");
File file2 = new File("D:\\IO\\hi.txt");
boolean renameTo = file2.renameTo(file1);
System.out.println(renameTo);
}
File类的判断功能
- public boolean isDirectory():判断是否是文件目录
- public boolean isFile() :判断是否是文件
- public boolean exists() :判断是否存在
- public boolean canRead() :判断是否可读
- public boolean canWrite() :判断是否可写
- public boolean isHidden() :判断是否隐藏
File类的创建功能
- public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
- public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。 如果此文件目录的上层目录不存在,也不创建。
- public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建
注意事项:如果你创建文件或者文件目录没有写盘符路径,那么,默认在项目 路径下。
File类的删除功能
- public boolean delete():删除文件或者文件夹
删除注意事项: Java中的删除不走回收站。 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
IO流原理及流的分类
Java IO原理
I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。
Java程序中,对于数据的输入/输出操作以“流(stream)” 的 方式进行。
java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。
输入input:读取外部数据(磁 盘、光盘等存储设备的数据)到程序(内存)中。
输出output:将程序(内存) 数据输出到磁盘、光盘等存储设备中。
流的分类
- 按操作数据单位不同分为:字节流(8 bit),字符流(16 bit)
- 按数据流的流向不同分为:输入流,输出流
- 按流的角色的不同分为:节点流,处理流
- Java的IO流共涉及40多个类,实际上非常规则,都是从如上4个 抽象基类派生的。
- 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。
IO 流体系
节点流和处理流
-
节点流:直接从数据源或目的地读写数据
-
处理流:不直接连接到数据源或目的地,而是“连接”在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提供更为强大的读写功能。
InputStream & Reader
- InputStream 和 Reader 是所有输入流的基类。
- 程序中打开的文件 IO 资源不属于内存里的资源,垃圾回收机制无法回收该资源,所以应该显式关闭文件 IO 资源。
- FileInputStream 从文件系统中的某个文件中获得输入字节。FileInputStream 用于读取非文本数据之类的原始字节流。要读取字符流,需要使用 FileReader
InputStream
- int read()
- 从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因 为已经到达流末尾而没有可用的字节,则返回值 -1。
- int read(byte[] b)
- 从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。如果因为已 经到达流末尾而没有可用的字节,则返回值 -1。否则以整数形式返回实际读取的字节数。
- int read(byte[] b, int off,int len)
- 将输入流中最多 len 个数据字节读入 byte 数组。尝试读取 len 个字节,但读取的字节也可能小于该值。以整数形式返回实际读取的字节数。如果因为流位于文件末尾而没有可用的字节,则返回值 -1。
- public void close() throws IOException
- 关闭此输入流并释放与该流关联的所有系统资源。
Reader
- int read()
- 读取单个字符。作为整数读取的字符,范围在 0 到 65535 之间 (0x00-0xffff)(2个 字节的Unicode码),如果已到达流的末尾,则返回 -1
- int read(char[] cbuf)
- 将字符读入数组。如果已到达流的末尾,则返回 -1。否则返回本次读取的字符数。
- int read(char[] cbuf,int off,int len)
- 将字符读入数组的某一部分。存到数组cbuf中,从off处开始存储,最多读len个字符。如果已到达流的末尾,则返回 -1。否则返回本次读取的字符数。
- public void close() throws IOException
- 关闭此输入流并释放与该流关联的所有系统资源。
@Test
public void testFileReader() {
FileReader fr = null;
try {
//1.实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");//相较于当前Module
//2.提供具体的流
fr = new FileReader(file);
//3.数据的读入
//read():返回读入的一个字符。如果达到文件末尾,返回-1
char[] ch = new char[10];
int len;
while((len = fr.read(ch)) != -1){
System.out.println(new String(ch,0,len));;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流的关闭操作
try {
if(fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OutputStream & Writer
- 因为字符流直接以字符作为操作单位,所以 Writer 可以用字符串来替换字符数组, 即以 String 对象作为参数
- FileOutputStream 从文件系统中的某个文件中获得输出字节。FileOutputStream 用于写出非文本数据之类的原始字节流。要写出字符流,需要使用 FileWriter
OutputStream
- void write(int b)
- 将指定的字节写入此输出流。write 的常规协定是:向输出流写入一个字节。要写 入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。 即写入0~255范围的。
- void write(byte[] b)
- 将 b.length 个字节从指定的 byte 数组写入此输出流。write(b) 的常规协定是:应该 与调用 write(b, 0, b.length) 的效果完全相同。
- void write(byte[] b,int off,int len)
- 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
- public void flush()throws IOException
- 刷新此输出流并强制写出所有缓冲的输出字节,调用此方法指示应将这些字节立 即写入它们预期的目标。
- public void close() throws IOException
- 关闭此输出流并释放与该流关联的所有系统资源。
Writer
- void write(int c)
- 写入单个字符。要写入的字符包含在给定整数值的 16 个低位中,16 高位被忽略。 即 写入0 到 65535 之间的Unicode码。
- void write(char[] cbuf)
- 写入字符数组。
- void write(char[] cbuf,int off,int len)
- 写入字符数组的某一部分。从off开始,写入len个字符
- void write(String str)
- 写入字符串。
- void write(String str,int off,int len)
- 写入字符串的某一部分。
- void flush()
- 刷新该流的缓冲,则立即将它们写入预期目标。
- public void close() throws IOException
- 关闭此输出流并释放与该流关联的所有系统资源。
//从内存中写出数据到硬盘的文件里
//1. 输出操作,对应的File可以不存在的。并不会报异常
// 2.File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。File对应的硬盘中的文件如果存在:
//如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
//如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
@Test
public void testFileWriter() {
FileWriter fw = null;
try {
//1.提供File类的对象,指明写出到的文件
File file = new File("hello1.txt");
//2.提供FileWriter的对象,用于数据的写出
fw = new FileWriter(file,false);
//3.写出的操作
fw.write("I have a dream!\n");
fw.write("We have a dream !");
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流资源的关闭
try {
if(fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- 复制文本
@Test
public void testFileReaderFileWriter(){
FileReader fr = null;
FileWriter fw = null;
try {
//1.创建File类的对象,指明读入和写出的文件
File srcFile = new File("rw.next");
File destFile = new File("rw1");
//2.创建输入流和输出流的对象
fr = new FileReader(srcFile);
fw = new FileWriter(destFile);
//3.数据的读入和写出操作
char[] cbuf = new char[5];
int len;//记录每次读入到cbuf中的字符的个数
while((len = fr.read(cbuf)) != -1){
//每次写出len个字符
fw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关闭流资源
try {
if(fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
节点流(或文件流)
读取文件
写入文件
- 定义文件路径时,注意:可以用“/”或者“\”。
- 在写入一个文件时,如果使用构造器FileOutputStream(file),则目录下有同名文件将被覆盖。
- 如果使用构造器FileOutputStream(file,true),则目录下的同名文件不会被覆盖, 在文件内容末尾追加内容。
- 在读取文件时,必须保证该文件已存在,否则报异常。
- 字节流操作字节,比如:.mp3,.avi,.rmvb,mp4,.jpg,.doc,.ppt
- 字符流操作字符,只能操作普通文本文件。最常见的文本文件:.txt,.java,.c,.cpp 等语言的源代码。尤其注意.doc,excel,ppt这些不是文本文件。
缓冲流
为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。
缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:
BufferedInputStream(read(byte[] buffer) 和 BufferedOutputStream (write(byte[] buffer,0,len) / flush())
BufferedReader(read(char[] cbuf) / readline()) 和 BufferedWriter(write(char[] cbuf,0,len) / flush())
- 当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区 。
- 当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从 文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中 读取下一个8192个字节数组。
- 向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满, BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法 flush()可以强制将缓冲区的内容全部写入输出流。
- 关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也 会相应关闭内层节点流 。
- flush()方法的使用:手动将buffer中内容写入文件 。
//实现非文本文件的复制
@Test
public void BufferedStreamTest(){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File("图片.jpg");//参数填想要复制的非文本文件的名称
File destFile = new File("图片1.jpg");
//2.造流
//节点流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[10];
int len;
while ((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
//要求:先关闭外层的流,再关闭内层的流
//关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
转换流
转换流提供了在字节流和字符流之间的转换
字节流中的数据都是字符时,转成字符流操作更高效。
转换流属于字符流
InputStreamReader
实现将字节的输入流按指定字符集转换为字符的输入流。 \
- 构造器·
- public InputStreamReader(InputStream in)
- public InputSreamReader(InputStream in,String charsetName)
//nputStreamReader的使用,实现字节的输入流到字符的输入流的转换
@Test
public void test(){
InputStreamReader isr = null;
try {
FileInputStream fis = new FileInputStream("abcd.txt");
//InputStreamReader isr = new InputStreamReader(fis);//使用默认的字符集
//参数二指明了字符集。字符集取决于文件abcd.txt保存时使用的字符集
isr = new InputStreamReader(fis,"utf-8");
char[] cbuf = new char[1024];
int len;
while ((len = isr.read(cbuf)) != -1){
String str = new String (cbuf,0,len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(isr != null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OutputStreamWriter
实现将字符的输出流按指定字符集转换为字节的输出流。
- 构造器
- public OutputStreamWriter(OutputStream out)
- public OutputSreamWriter(OutputStream out,String charsetName)
@Test
public void test1(){
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
//1.造文件、造流
File file1 = new File("bcde.txt");
File file2 = new File("bcde_gbk.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
isr = new InputStreamReader(fis,"utf-8");
osw = new OutputStreamWriter(fos,"gbk");
//2.读写过程
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
osw.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//3.关闭资源
if(isr != null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(osw !=null){
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
标准输入、输出流
System.in:标准的输入流,默认从键盘输入
System.out:标准的输出流,默认从控制台输出
System类的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定输入和输出的流。
打印流
实现将基本数据类型的数据格式转化为字符串输出
打印流:PrintStream和PrintWriter
- 提供了一系列重载的print()和println()方法,用于多种数据类型的输出
- PrintStream和PrintWriter的输出不会抛出IOException异常
- PrintStream和PrintWriter有自动flush功能
- PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。
- 在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
- System.out返回的是PrintStream的实例
数据流
DataInputStream 和 DataOutputStream
作用:用于读取或写出基本数据类型的变量或字符串
对象流
ObjectInputStream和OjbectOutputSteam
用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可 以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
对象的序列化
- 对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从 而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传 输到另一个网络节点。当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
- 序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据, 使其在保存和传输时可被还原
作用:用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
要想一个java对象是可序列化的,需要满足相应的要求:
- 需要实现接口:Serializable
- 当前类提供一个全局常量:serialVersionUID
- 除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性也必须是可序列化的。(默认情况下,基本数据类型可序列化)
- ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量: private static final long serialVersionUID;
serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象 进行版本控制,有关各版本反序列化时是否兼容。
如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自 动生成的。若类的实例变量做了修改,serialVersionUID 可能发生变化。故建议, 显式声明。
使用对象流序列化对象
若某个类实现了 Serializable 接口,该类的对象就是可序列化的:
创建一个 ObjectOutputStream
调用 ObjectOutputStream 对象的 writeObject(对象) 方法输出可序列化对象
注意写出一次,操作flush()一次
反序列化
创建一个 ObjectInputStream
调用 readObject() 方法读取流中的对象
强调:如果某个类的属性不是基本数据类型或 String 类型,而是另一个 引用类型,那么这个引用类型必须是可序列化的,否则拥有该类型的 Field 的类也不能序列化
序列化机制:
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。当其它程序获取了这种二进制流,就可以恢复成原来的Java对象。
随机存取文件流
RandomAccessFile类
- RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。并 且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写。
- RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意地方来读、写文件 (支持只访问文件的部分内容 ;可以向已存在的文件后追加内容 )
- RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。 RandomAccessFile 类对象可以自由移动记录指针:
long getFilePointer():获取文件记录指针的当前位置
void seek(long pos):将文件记录指针定位到 pos 位置
- 构造器
public RandomAccessFile(File file, String mode)
public RandomAccessFile(String name, String mode)- 创建 RandomAccessFile 类实例需要指定一个 mode 参数,该参数指定 RandomAccessFile 的访问模式:
r: 以只读方式打开
rw:打开以便读取和写入
rwd:打开以便读取和写入;同步文件内容的更新
rws:打开以便读取和写入;同步文件内容和元数据的更新
如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)