10.1 File类10.2 IO流原理、分类
IO流概述FileReaderFileWriter 10.3 处理流
*缓冲流*转换流标准输入输出流打印流数据流*对象流随机存取文件流
10.1 File类java.io.File类的一个对象,代表一个文件或文件目录
构造器创建File实例:
- File(String filePath)File(String parent, File child)File(File parent, String child)
路径分隔符:
windows和DOS系统默认使用“”表示
UNIX和URL使用“/”表示
为了解决此隐患,File类提供了一个常量public static final String separator:根据 *** 作系统动态的提供分隔符
注:
Idea中:Junit单元测试方法中相对路径为当前module下,main()方法中相对路径为当前project下Eclipse中:两种方法的相对路径都为当前project下
File类中涉及到关于文件(目录)的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入或读取文件内容的 *** 作。如需读取或写入文件内容,必须使用IO流来完成
后续File类的秀爱给你常会作为参数传递到流的构造器中,指明读取或写入的“终点”
常用方法:
- String getAbsolutePath():获取绝对路径String getPath():获取路径String getName():获取名称String getParent():获取上层文件目录路径,若无返回nulllong length():获取文件长度(字节数),不能获取目录长度long lastModified():获取最后一次修改时间,毫秒值boolean renameTo(File dest):将此文件重命名为指定的文件路径
要求:此文件在硬盘中存在,dest文件在硬盘中不存在 boolean exists():判断是否存在boolean isDirectory():判断是否是文件目录boolean isFile():判断是否是文件boolean canRead():判断是否可读boolean canWrtite():判断是否可写boolean isHidden():判断是否是隐藏的
如下方法适用于文件目录:
- String[ ] list():获取指定目录下的所有文件或文件目录的名称数组File[ ] listFiles():获取指定目录下的所有文件或文件目录的File数组
创建文件(目录)
boolean createNewFile():创建文件,若文件已存在则不创建,返回false
File file = new File("create.txt"); if(!file.exists()){ file.createNewFile(); System.out.println("创建成功!"); }else{ file.delete(); System.out.println("删除成功!"); }
boolean mkdir():创建文件目录,若已存在或上层目录不存在则不创建,返回false
boolean mkdirs():创建文件目录,若上层目录不存在,则一并创建
删除文件(目录)
boolean delete():删除文件(目录),若文件目录中有内容则不删除,返回false
10.2 IO流原理、分类 IO流概述
IO:Input / Output的缩写,处理设备之间的数据传输,如读写文件、网络通讯等
流:数据的输入输出的标准化方式
流的分类
按 *** 作数据单位:
字节流(8bit)图片、视频字符流(16bit)文本 按数据流流向:输入流、输出流按流的角色:节点流、处理流
(抽象基类) 字节流 字符流
由这四个类派生出来的子类名都是以其父类名作为后缀的
IO流体系
输入输出的标准化过程
- 输入过程
- 创建File类的对象,指明读取的数据的来源(要求此文件一定存在创建相应的输入流,将File类的对象作为参数,传入流的构造器中具体的读入过程:创建相应的byte[]或char[]关闭流资源
- 创建File类的对象,指明读取的数据的来源(此文件可以不存在创建相应的输出流,将File类的对象作为参数,传入流的构造器中具体的写出过程:write(char[] / byte[] buffer,0,len)关闭流资源
说明:程序中出现的编译时异常要使用try-catch0finally处理
FileReaderread():返回读入的一个字符,如果达到末尾则返回-1
//1、实例化File类的对象,指明要 *** 作的文件 File file = new File("hello.txt"); FileReader fr = null; //2、将文件作为形参,提供具体的流 try { fr = new FileReader(file); //3、数据的读入 int data; while ((data = fr.read()) != -1) { System.out.println((char) data); } }catch (IOException e){ e.printStackTrace(); }finally { //4、流的关闭 *** 作 try { if(fr!=null) fr.close(); } catch (IOException e) { e.printStackTrace(); } }
说明:
- read():返回读入的一个字符,如果达到末尾则返回-1异常处理:为了保证流资源一定可以执行关闭 *** 作,需要用try-catch-finally处理读入的文件一定要存在,否则就会报FileNotFoundException
read(char[ ] cbuf):返回每次读入cbuf数组的字符个数,如果到达文件末尾则返回-1
File file = new File("hello.txt"); FileReader fr = null; try { fr = new FileReader(file); char[] cbuf = new char[5]; int len; //read(char[] cbuf):返回每次读入cbuf数组的字符个数,如果到达文件末尾则返回-1 // 方式一 // while((len=fr.read(cbuf))!=-1){ // for (int i = 0; iFileWriter File file = new File("hello1.txt"); FileWriter fw = null; try { fw = new FileWriter(file); fw.write("I have a dream!n".toCharArray()); fw.write("you need to have a dream"); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fw!=null) fw.close(); } catch (IOException e) { e.printStackTrace(); } }说明:
输出 *** 作:对应的File可以不存在
若File不存在,则在输出的过程中自动创建若File存在:
如果流使用的构造器是:FileWriter(file,false)或FileWriter(file),则对原有文件内容进行覆盖如果流使用的构造器是:FileWriter(file,true),则在原有文件内容末尾进行添加
练习:
File字符流复制文本文件
File srcFile = new File("hello.txt"); File tgtFile = new File("hello2.txt"); FileReader fr = null; FileWriter fw = null; try { fr = new FileReader(srcFile); fw = new FileWriter(tgtFile); char[] cbuf = new char[5]; int len; while((len = fr.read(cbuf))!=-1){ fw.write(cbuf,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if(fw!=null) fw.close(); } catch (IOException e) { e.printStackTrace(); } try { if(fr!=null) fr.close(); } catch (IOException e) { e.printStackTrace(); } }FileInputStream、FileOutputStream与FileReader、FileWriter的用法类似
结论:
对于文本文件(.txt,.java,.c,.cpp),使用字符流FileReader、FileWriter处理对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt),使用字节流FileInputStream、FileOutputStream处理如果只是复制文件,可以用字节流复制文本文件(只传输不打印),但不可用字符流复制非文本文件
10.3 处理流 *缓冲流
缓冲流:
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
作用:提高流的读取、写入的速度
原因:内部提供了一个缓冲区
处理流,就是“套接”在已有的流上
练习:
缓冲流BufferedInputStream、BufferedOutputStream复制非文本文件
public void copyFile(String srcfile, String destfile) { File srcFile = new File(srcfile); File destFile = new File(destfile); FileInputStream fis = null; FileOutputStream fos = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bis != null) bis.close(); } catch (IOException e) { e.printStackTrace(); } try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); } } }要求:先关闭外层处理流,再关闭内层节点流
说明:关闭外层流时,内层流也会自动关闭,因此可以省略内层流的关闭 *** 作
练习:
缓冲流BufferedReader、BufferedWriter复制文本文件
public void copyFile(String srcfile, String desffile){ BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader(new File(srcfile))); bw = new BufferedWriter(new FileWriter(new File(desffile))); char[] cbuf = new char[1024]; // 方法一: // int len; // while((len=br.read(cbuf))!=-1){ // bw.write(cbuf,0,len); // } // 方法二: String data; while((data=br.readLine())!=null){ // bw.write(data+"n"); bw.write(data); bw.newline(); } // readLine()不包含换行符,需要手动添加 } catch (IOException e) { e.printStackTrace(); } finally { try { if(br!=null){ br.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(bw!=null){ bw.close(); } } catch (IOException e) { e.printStackTrace(); } } }*转换流
转换流:属于字符流
InputStreamReader:将一个字节的输入流转换为字符的输入流(解码)
OutputStreamWriter:将一个字符的输出流转换为字节的输出流
作用:提供字节流与字符流之间的转换(编码)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-byaArK4f-1642867698063)(C:UsersHPAppDataRoamingTyporatypora-user-imagesimage-20220121110642231.png)]
public void test() throws IOException { FileInputStream fis = new FileInputStream("text.txt"); InputStreamReader isr = new InputStreamReader(fis,"utf-8"); //参数2指明了字符集,取决于要读写的文件使用的字符集 char[] cbuf = new char[20]; int len; while((len=isr.read(cbuf))!=-1){ System.out.print(new String(cbuf,0,len)); } isr.close(); }标准输入输出流
System.in:标准输入流:默认从键盘输入
System.out:标准输出流:默认从控制台输出
通过System类的setIn()、setOut()方法可对默认设备进行更改
public static void setIn(InputStream in)public static void setOut(PrintStream out)
练习:从键盘输入字符串,不断将读取到的整行字符串转换成大写输出,直至输入e或exit时退出程序
public static void main(String[] args) { BufferedReader br = null; try { InputStream in = System.in; //字节流 InputStreamReader isr = new InputStreamReader(in); //用转换流将字节流转换为字符流 br = new BufferedReader(isr); while (true) { System.out.println("请输入字符串:"); String str = br.readLine(); if(str == null || "e".equalsIgnoreCase(str) || "exit".equalsIgnoreCase(str)) break; System.out.println(str.toUpperCase()); } System.out.println("goodbye!"); } catch (IOException e) { e.printStackTrace(); } finally { try { if(br!=null) br.close(); } catch (IOException e) { e.printStackTrace(); } } }打印流PrintStream和PrintWriter
提供了一系列重载的print()和println()方法,输出多种数据类型输出不会抛IOException异常有自动flush功能PrintStream打印的所有字符都使用平台默认字符编码转换为字节
在需要写入字符而不是字节的情况下,应该使用PrintWriter类 System.out返回的是PrintSream类
练习:设置文件输出打印流
public void test2() throws IOException { FileOutputStream fos = new FileOutputStream("printStream.txt"); // 创建打印输出流,设置为自动刷新flush模式(写入换行符或字节'n'时会自动刷新输出缓冲区 PrintStream ps = new PrintStream(fos,true); System.setOut(ps); for(int i=0;i<256;i++){ System.out.print((char)i); if(i%50==0) System.out.println(); } ps.close(); }数据流DataInputStream和DataOutputStream作用:读取、写出基本数据类型或字符串变量
注:读取各类型数据的顺序要与写入文件时的顺序一致
练习:
public void test3() throws IOException { DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt")); dos.writeUTF("刘德华"); dos.writeInt(23); dos.writeBoolean(true); dos.close(); } public void test4() throws IOException { DataInputStream dos = new DataInputStream(new FileInputStream("data.txt")); String name = dos.readUTF(); int age = dos.readInt(); boolean male = dos.readBoolean(); System.out.println("name = " + name); System.out.println("age = " + age); System.out.println("male = " + male); dos.close(); }*对象流ObjectInputStream和ObjectOutputStream作用:用于存储和读取基本数据类型数据或对象的处理流,可以把Java中的对象写入到数据源中(序列化),也能把对象从数据源中还原回来(反序列化)
对象需要满足如下的要求,方可序列化
所在类要实现Serializable接口所在类要声明一个全局常量:public static final long serialVersionUID = xxxxxxxxxL; (为了版本控制)除了所在类要实现Serializable接口之外,还必须保证类内部所有属性也是可序列化的(默认情况下,基本数据类型可序列化)
补充:不能序列化static和transient修饰的成员
序列化过程:将内存中的Java对象保存到磁盘中或通过网络传输出去,使用ObjectOutputStream实现
public void test(){ ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("obj.dat")); oos.writeObject(new String("我爱北京天安门")); oos.flush(); //刷新 *** 作 } catch (IOException e) { e.printStackTrace(); } finally { try { if(oos!=null) oos.close(); }catch (IOException e) { e.printStackTrace(); } } }反序列化过程:将磁盘文件、网络流中的对象还原为内存中的一个java对象,需要使用ObjectInputStream实现
public void test1(){ ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("obj.dat")); Object obj = ois.readObject(); String str = (String)obj; System.out.println(str); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if(ois!=null) try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } }随机存取文件流RandomAccessFile
RandomAccessFile直接继承于Object类实现了DataInput、DataOutput接口,意味着这个类既可以读也可以写作为输出流时,如果写出的文件不存在则自动创建,如果存在则会对原有内容进行覆盖(默认从头开始覆盖)可以通过reek调整指针,实现“插入”数据
构造器
public RandomAccessFile(File file, String mode)public RandomAccessFile(String name, String mode)mode参数指定RandomAccessFile的访问模式:
r:以只读方式打开
rw:打开以便读取和写入
rwd:打开以便读取和写入;同步文件内容的更新
rws:打开以便读取和写入;同步文件内容和元数据的更新
public void test2() throws IOException{ RandomAccessFile raf = new RandomAccessFile("hello.txt", "rw"); raf.seek(3);//将指针调到角标为3的位置 raf.write("xyz".getBytes()); raf.close(); }通过reek调整指针,实现“插入”数据
public void test3() throws IOException { int pos = 3; File file = new File("hello.txt"); RandomAccessFile raf = new RandomAccessFile(file,"rw"); raf.seek(pos); byte[] buffer = new byte[20]; int len; // 保存指针pos后的所有数据到StringBuilder中 StringBuilder str = new StringBuilder((int) file.length()); while((len=raf.read(buffer))!=-1){ str.append(new String(buffer,0,len)); } // 调回指针,写入xyz raf.seek(pos); raf.write("xyz".getBytes()); raf.write(str.toString().getBytes()); raf.close(); }我的学习笔记有更多精彩内容哦
Java编程知识专栏欢迎分享,转载请注明来源:内存溢出
评论列表(0条)