JavaIO流
2021/10/7 20:42:59
本文主要是介绍JavaIO流,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
JavaIO流
- File类的使用
- 如何创建File类的实例
- 常用方法
- IO流原理及流的分类
- Java IO原理
- 流的分类
- IO流体系
- 读取数据(字符流)
- 写出数据(字符流)
- 字节流
- 缓冲流(处理流的一种)
- 转换流(处理流的一种)
- 对象流
- 对象的序列化
File类的使用
- File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
- File类声明在java.io包下
如何创建File类的实例
-
public File(String pathname)
-
以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果 pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。
- 绝对路径:是一个固定的路径,从盘符开始
- 相对路径:是相对于某个位置开始
-
File file1 = new File("hello.txt"); //相对于当前module File file2 = new File("E:\\Project\\java\\IdeaProjects\\workspace_idea1\\JavaSenior\\day08\\he.txt");
-
-
public File(String parent,String child)
-
以parent为父路径,child为子路径创建File对象
-
File file3 = new File("E:\\Project\\java\\IdeaProjects\\workspace_idea1","JavaSenior");
-
-
public File(File parent,String child)
-
根据一个父File对象和子文件路径创建File对象
-
File file4 = new File(file3,"hi.txt");
-
说明:
IDEA中:
- 如果开发使用Junit中的单元测试方法测试,相对路径即为当前Module下
- 如果大家使用main()测试,相对路径即为当前Project下
Eclipse中:
- 不管使用单元测试方法还是使用main()测试,相对路径都是当前的Project下。
路径分隔符
-
路径中的每级目录之间用一个路径分隔符隔开。
-
路径分隔符和系统有关:
- windows和DOS系统默认使用“\”来表示
- UNIX和URL使用“/”来表示
-
Java程序支持跨平台运行,因此路径分隔符要慎用
-
为了解决这个隐患,File类提供了一个常量:
-
public static final String separator。根据操作系统,动态的提供分隔符。
-
File file1 = new File("d:\\atguigu\\info.txt"); File file2 = new File("d:" + File.separator + "atguigu" + File.separator + "info.txt"); File file3 = new File("d:/atguigu");
-
常用方法
**File类的获取功能 **
-
public String getAbsolutePath():获取绝对路径
-
public String getPath() :获取路径
-
public String getName() :获取名称
-
public String getParent():获取上层文件目录路径。若无,返回null
-
public long length() :获取文件长度(即:字节数)。不能获取目录的长度
-
public long lastModified() :获取最后一次的修改时间,毫秒值
如下两个方法适用于文件目录:
-
public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
-
public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
代码举例一:
File file1 = new File("hello.txt"); //文件存在 File file2 = new File("C:\\Users\\17527\\Desktop\\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());
输出如下:
E:\Project\java\IdeaProjects\workspace_idea1\JavaSenior\day08\hello.txt hello.txt hello.txt null 10 Tue Apr 13 15:34:13 CST 2021 *************************** C:\Users\17527\Desktop\hi.txt C:\Users\17527\Desktop\hi.txt hi.txt C:\Users\17527\Desktop 0 0
代码举例二:
File file = new File("E:\\Picture"); String[] list = file.list(); for (String str: list){ System.out.println(str); } File[] files = file.listFiles(); for (File f : files){ System.out.println(f); }
输出如下:
1607663557663.jpg game QQ浏览器截图 Typora 图片素材 壁纸 截图 E:\Picture\1607663557663.jpg E:\Picture\game E:\Picture\QQ浏览器截图 E:\Picture\Typora E:\Picture\图片素材 E:\Picture\壁纸 E:\Picture\截图
File类的重命名功能
- public boolean renameTo(File dest):把文件重命名为指定的文件路径
比如:file1.renameTo(file2)为例:
要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
File file1 = new File("hello.txt"); File file2 = new File("C:\\Users\\17527\\Desktop\\hi.txt"); boolean b = file1.renameTo(file2); System.out.println(b);
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中的删除不走回收站。
要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
总结:
- File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,并为涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。
- 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的“终点”。
IO流原理及流的分类
Java IO原理
- I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等
- Java程序中,对于数据的输入/输出操作以“流(stream)” 的方式进行。
- java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据
- 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。
- 输出output:将程序(内存) 数据输出到磁盘、光盘等存储设备中
流的分类
- 按操作数据单位不同分为:字节流(8 bit),字符流(16 bit)
- 按数据流的流向不同分为:输入流,输出流
- 按流的角色的不同分为:节点流,处理流
IO流体系
分辨流看后面
读取数据(字符流)
将day09下的hello.txt文件内容读入程序中,并输出到控制台
说明点:
- read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1
- 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
- 读入的文件一定要存在,否则就会报FileFoundException。
读取数据的规范步骤:
- File类的实例化
- FileReader流的实例化
- 读入的操作
- 资源的关闭
//对read()操作升级:使用read的重载方法 @Test public void testFileReader1(){ FileReader fileReader = null; try { //1.File类的实例化 File file = new File("hello.txt"); //2.FileReader流的实例化 fileReader = new FileReader(file); //3.读入的操作 //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1 //比如这个例子第一次读入5个,len就是5,第二次读入5个,len就是5,第三次读入3个,len就为3 char[] cbuf = new char[5]; int len; while ((len = fileReader.read(cbuf)) != -1){ //错误的写法: // for (int i = 0;i < cbuf.length;i++){ // System.out.print(cbuf[i]); //helloWorld123ld // } //正确的写法: // for (int i = 0;i < len;i++){ // System.out.print(cbuf[i]); // } //方式二: //错误的写法,对应着方式一的错误的写法 // String str = new String(cbuf); // System.out.print(str); helloWorld123ld //正确的写法: String str = new String(cbuf,0,len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { if (fileReader != null) //4.资源的关闭 { try { fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } }
写出数据(字符流)
写出数据的步骤规范:
- 提供File类的对象,指明写出到的文件
- 提供FileWriter的对象,用于数据的写出
- 写出的操作
- 流资源的关闭
@Test public void testFileWriter() { FileWriter fileWriter = null; try { //1.提供File类的对象,指明写出的文件 File file = new File("hello1.txt"); //2.提供FileWriter的对象,用于数据的写出 fileWriter = new FileWriter(file, true); //3.写出的操作 fileWriter.write("I hava a dream!\n"); fileWriter.write("you need to have a dream!"); } catch (IOException e) { e.printStackTrace(); } finally { if (fileWriter != null) { //4.流资源的关闭 try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } }
说明:
- 输出操作,对应的File可以不存在的。并不会报异常
- File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
- File对应的硬盘中的文件如果存在:
- 如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
- 如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
- File对应的硬盘中的文件如果存在:
文件的读取与写入(复制操作)
@Test public void testFileReaderFileWriter() { FileReader fileReader = null; FileWriter fileWriter = null; try { //1.创建File类的对象,指明读入和写出的文件 File srcFile = new File("hello.txt"); File descFile = new File("hello2.txt"); //不能使用字符流来处理图片等字节数据 // File srcFile = new File("1607663557663.jpg"); // File descFile = new File("1607.jpg"); //2.创建输入流和输出流的对象 fileReader = new FileReader(srcFile); fileWriter = new FileWriter(descFile); //3.数据的读入和写出操作 char[] cbuf = new char[5]; int len; //记录每次读入到cbuf数组中的字符的个数 while ((len = fileReader.read(cbuf)) != -1) { //每次写出len个字符 fileWriter.write(cbuf, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { //4.关闭流资源 //方式一: // try { // if (fileReader != null) // fileReader.close(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // try { // if (fileReader != null) // fileWriter.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } //方式二: try { if (fileReader != null) fileReader.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fileReader != null) fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
这里注意处理两个流资源的关闭可以用两个try-catch。因为try-catch是等于真正的处理掉了异常,所以后面的代码一样会执行
字节流
实现对图片的复制操作
@Test public void testFileInputOutoutSteam() { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { File srcFile = new File("1607663557663.jpg"); File destFile = new File("11111111.jpg"); fileInputStream = new FileInputStream(srcFile); fileOutputStream = new FileOutputStream(destFile); byte[] buffer = new byte[5]; int len; while ((len = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileInputStream != null) fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fileOutputStream != null) fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
指定路径下文件的复制
public void copyFile(String srcPath, String destPath) { FileInputStream fis = null; FileOutputStream fos = null; try { // File srcFile = new File(srcPath); File destFile = new File(destPath); // fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); //复制的过程 byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { fos.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { // try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void testCopyFile() { long start = System.currentTimeMillis(); String srcPath = "C:\\Users\\17527\\Desktop\\不知火.mp4"; String destPath = "C:\\Users\\17527\\Desktop\\不知火1.mp4"; // String srcPath = "hello.txt"; // String destPath = "hello3.txt"; copyFile(srcPath, destPath); long end = System.currentTimeMillis(); System.out.println("复制操作花费的时间为:" + (end - start));//2429 } }
结论:
- 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
- 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理
- 字节流也可以来实现文本文件的复制,因为这里复制操作没有经过控制台
缓冲流(处理流的一种)
-
为了提高数据读写的速度,Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区。
缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为: -
BufferedInputStream 和 BufferedOutputStream
-
BufferedReader 和 BufferedWriter
代码举例:
public class BufferedTest { /* 实现对非文本文件的复制 */ @Test public void BufferedSteamTest(){ FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; BufferedInputStream bufferedInputStream = null; BufferedOutputStream bufferedOutputStream = null; try { //1.造文件 File srcFile = new File("1607663557663.jpg"); File destFle = new File("2222222.jpg"); //2.造流 //2.1 造节点流 fileInputStream = new FileInputStream(srcFile); fileOutputStream = new FileOutputStream(destFle); //2.2 造缓冲流 bufferedInputStream = new BufferedInputStream(fileInputStream); bufferedOutputStream = new BufferedOutputStream(fileOutputStream); //3.复制的细节:读取、写入的过程 byte[] buffer = new byte[10]; int len; while ((len = bufferedInputStream.read(buffer)) != -1){ bufferedOutputStream.write(buffer,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { //4.资源关闭 //要求:先关闭外层的流,再关闭内层的流 try { if(bufferedInputStream != null) bufferedInputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { if (bufferedOutputStream != null) bufferedOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略不写。 // fileInputStream.close(); // fileOutputStream.close(); } } //实现文件复制的方法 public void copyFileWithBuffered(String srcPath,String destPath){ FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; BufferedInputStream bufferedInputStream = null; BufferedOutputStream bufferedOutputStream = null; try { //1.造文件 File srcFile = new File(srcPath); File destFle = new File(destPath); //2.造流 //2.1 造节点流 fileInputStream = new FileInputStream(srcFile); fileOutputStream = new FileOutputStream(destFle); //2.2 造缓冲流 bufferedInputStream = new BufferedInputStream(fileInputStream); bufferedOutputStream = new BufferedOutputStream(fileOutputStream); //3.复制的细节:读取、写入的过程 byte[] buffer = new byte[1024]; int len; while ((len = bufferedInputStream.read(buffer)) != -1){ bufferedOutputStream.write(buffer,0,len); // bufferedOutputStream.flush();//刷新缓冲区 } } catch (IOException e) { e.printStackTrace(); } finally { //4.资源关闭 //要求:先关闭外层的流,再关闭内层的流 try { if(bufferedInputStream != null) bufferedInputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { if (bufferedOutputStream != null) bufferedOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略不写。 // fileInputStream.close(); // fileOutputStream.close(); } } @Test public void test(){ long start = System.currentTimeMillis(); copyFileWithBuffered("C:\\Users\\17527\\Desktop\\不知火.mp4","C:\\Users\\17527\\Desktop\\不知火2.mp4"); long end = System.currentTimeMillis(); System.out.println("花费的时间为:" + (end - start)); //652 } /* 使用BufferedReader和BuferedWriter实现文本文件的复制 */ @Test public void testBufferedReaderBufferedWriter(){ BufferedReader br = null; BufferedWriter bw = null; try { //创建文件和相应的流 br = new BufferedReader(new FileReader(new File("dbcp.txt"))); bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt"))); //读写操作 //方式一:使用char[]数组 // char[] cbuf = new char[1024]; // int read; // while ((read = br.read(cbuf)) != -1){ // bw.write(cbuf,0,read); // } //方式二:使用String String data; while ((data = br.readLine()) !=null){ //readLine()一次读取一行数据,但是不会换行 //方法一: // bw.write(data + "\n");//data中不包含换行符 //方法二: bw.write(data);//data中不包含换行符 bw.newLine();//提供换行的操作 } } 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(); } } } }
readLine():一次读取一行数据,但是不会换行—> 在BufferedReader中可用
实现图片加密操作
byte[] buffer = new byte[1024]; int len; while ((len = fi.read(buffer)) != -1) { //字节数组进行修改 //错误的:这里修改的是新的变量,并不会对数组进行修改 // for (byte b:buffer){ // b = (byte)(b ^ 5); // } //正确的: for (int i = 0; i < len; i++) { buffer[i] = (byte)(buffer[i] ^ 5); } fo.write(buffer, 0, len);
m ^ n ^ n = n,所以解密过程就是把需要解密的文件再^5(加密)一次即可
转换流(处理流的一种)
- 转换流提供了在字节流和字符流之间的转换
- Java API提供了两个转换流:
- InputStreamReader:将InputStream转换为Reader
- OutputStreamWriter:将Writer转换为OutputStream
InputStreamReader
- 实现将字节的输入流按指定字符集转换为字符的输入流。
- 需要和InputStream“套接”。
- 构造器
- public InputStreamReader(InputStream in)
- public InputSreamReader(InputStream in,String charsetName)
OutputStreamWriter
- 实现将字符的输出流按指定字符集转换为字节的输出流。
- 需要和OutputStream“套接”。
- 构造器
- public OutputStreamWriter(OutputStream out)
- public OutputSreamWriter(OutputStream out,String charsetName)
代码举例:
/* 此时处理异常的话,仍然应该使用try-catch-finally InputStreamReader的使用,实现字节的输入流到字符的输入流的转换 */ @Test public void test1() throws IOException { FileInputStream fis = new FileInputStream("dbcp.txt"); // InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集,当前为utf-8 //参数2指明了字符集,具体使用哪个字符集,取决于文件dbcp.txt保存时的字符集 InputStreamReader isr = new InputStreamReader(fis,"UTF-8"); char[] cbuf = new char[20]; int len; while ((len = isr.read(cbuf)) != -1){ System.out.print(new String(cbuf,0,len)); } isr.close(); }
/* 综合使用InputStreamReader和OutputStreamWriter */ @Test public void test2() throws IOException { File file1 = new File("dbcp.txt"); File file2 = new File("dbcp_gdk.txt"); FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2); InputStreamReader isr = new InputStreamReader(fis,"utf-8"); OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk"); //读写过程 char[] cbuf = new char[20]; int len; while ((len = isr.read(cbuf)) != -1){ osw.write(cbuf,0,len); } osw.close(); isr.close(); }
对象流
-
ObjectInputStream和OjbectOutputSteam
- 用于存储和读取基本数据类型数据或==对象==的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
-
序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
-
反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
-
ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
对象的序列化
-
**对象序列化机制**允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传 输到另一个网络节点。//当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
-
序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据, 使其在保存和传输时可被还原
-
序列化是 RMI(Remote Method Invoke – 远程方法调用)过程的参数和返 回值都必须实现的机制,而 RMI 是 JavaEE 的基础。因此序列化机制是 JavaEE 平台的基础
-
如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。 否则,会抛出NotSerializableException异常
- Serializable
- Externalizable
-
凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:
- private static final long serialVersionUID;—序列版本号
- serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。
- 如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。若类的实例变量做了修改,serialVersionUID 可能发生变化。故建议,显式声明。
-
简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的 serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常。(InvalidCastException)
-
若某个类实现了 Serializable 接口,该类的对象就是可序列化的:
- 创建一个 ObjectOutputStream
- 调用 ObjectOutputStream 对象的 writeObject(对象) 方法输出可序列化对象
- 注意写出一次,操作flush()一次
-
反序列化
- 创建一个 ObjectInputStream
- 调用readObject() 方法读取流中的对象
强调:如果某个类的属性不是基本数据类型或 String 类型,而是另一个 引用类型,那么这个引用类型必须是可序列化的,否则拥有该类型的 Field 的类也不能序列化
这篇关于JavaIO流的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)