【文件IO流】
创始人
2025-05-30 14:03:22
0

文件IO流

      • 文件IO流
        • 一.什么是文件?
          • 1.文件流
          • 2.创建文件
          • 3.获取文件信息
          • 4.常见的文件操作
        • 二.什么是IO流?
          • 1.流的分类
          • 2. InputStream字节输入流
          • 3.FileOutputStream字节输出流
          • 4.文件拷贝
          • 5.字符流
          • 6.节点流和处理流

文件IO流

一.什么是文件?

​ 文件就是保存数据的地方

1.文件流

文件在程序中以的形式进行操作

  1. 流:数据在数据源(文件)和 程序(内存)之间经历的路径
  2. 输出流:java 程序(内存) ————> 文件(磁盘)
  3. 输入流: java 程序 (内存) <———— 文件(磁盘)
2.创建文件
  • 创建文件对象的相关构造器
new File(String pathname)           
new File(File parent,String child)          
new File(String parent,String child)             
  • 创建文件的方法 createNewFile()

  • 具体方法如下

// 1. new File(String pathname)方式  
public void create01() {String filename = "e:\\news1.txt";File file = new File(filename);try {file.createNewFile();System.out.println("文件创建成功");} catch (IOException e) {e.printStackTrace();System.out.println("文件创建失败");}}// 2. new File(File parent,String child)public void create02() {File parent = new File("e:\\");String childName = "news2.txt";File file = new File(parent, childName);try {file.createNewFile();System.out.println("文件创建成功");} catch (IOException e) {e.printStackTrace();System.out.println("文件创建失败");}}// 3. new File(String parent,String child)public void create03() {String parent = "e:\\";String child = "news3.txt";File file = new File(parent, child);try {file.createNewFile();System.out.println("文件创建成功");} catch (IOException e) {e.printStackTrace();System.out.println("文件创建失败");}}
3.获取文件信息
  • 注:UTF-8编码 一个英文字母一字节 一个汉字三字节 以hello世界为例:11字节
// 获取文件信息public void getInfo() {// 先创建文件对象File file = new File("e://news1.txt");if (file.exists()) {System.out.println("文件名:" + file.getName());System.out.println("文件路径:" + file.getPath());System.out.println("文件父目录: " + file.getParent());System.out.println("文件大小(单位字节):" + file.length());} else {System.out.println("该文件不存在");}}

获取文件信息

4.常见的文件操作
  • 删除文件 delete() 返回值为boolean类型
  • 创建目录 mkdir 一级目录 mkdirs 多级目录
    // 如果文件存在 则删除文件public void m1() {String filePath = "e:\\news1.txt";File file = new File(filePath);if (file.exists()) {System.out.println(filePath + " 文件存在");boolean flag = file.delete();if (flag) {System.out.println(filePath + " 文件被删除!!!");} else {System.out.println(filePath + " 文件删除失败~~~");}} else {System.out.println(filePath + " 文件不存在...");}}
    // mkdir创建一级目录 mkdirs 创建多级目录public void m2() {String directoryName = "e:\\demo";File file = new File(directoryName);if (file.exists()) {System.out.println(directoryName + " 目录已经存在");} else {boolean flag = file.mkdir();if (flag) {System.out.println(directoryName + " 目录创建成功");} else {System.out.println(directoryName + " 目录创建失败");}}}

二.什么是IO流?

  1. i/o 技术 input output 用于处理数据的传输 如:读写文件,网络通讯
  2. java程序中对数据的输入与输出以流stream的方式进行
  3. java.io包下提供各种流和数据
1.流的分类
  • 按操作数据单位不同分为:字节流(8bit)二进制文件 字符流(按字符) 文本文件 一个字符对应几个字节不确定
  • 按流的流向不同分为:输入流 输出流
  • 按流的角色不同分为:节点流 处理流/包装流
抽象基类字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter
2. InputStream字节输入流
  • FileInputStream: 文件输入流
  • BufferedInputStream: 缓冲字节输入流
  • ObjectInputStream:对象字节输入流

FileInputStream.read() 单个字节读取,效率比较低 返回值为int 需要强转为char

    /*** 演示读取文件*/@Testpublic void readFile01() {String filePath = "e:\\hello.txt";int readData = 0;FileInputStream fileInputStream = null;try {// 创建FileInputStream 用于读取文件fileInputStream = new FileInputStream(filePath);// 读取一个字节的内容 如果返回-1则读取完毕 (一个英文字母一个字节)while ((readData = fileInputStream.read()) != -1) {System.out.print((char) readData); //转成char形式}} catch (IOException e) {e.printStackTrace();} finally {// 关闭流,释放资源try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}

FileInputStream.read(byte[])

    /*** 使用read(byte[] b) 读取文件 提高效率*/@Testpublic void readFile02() {String filePath = "e:\\hello.txt";// 定义字节数组byte[] buf = new byte[8];  // 一次读取8个字节int readLength = 0;FileInputStream fileInputStream = null;try {// 创建FileInputStream 用于读取文件fileInputStream = new FileInputStream(filePath);// 按传入的字节数组进行读取//fileInputStream().read(buf)返回实际读取的字节数while ((readLength = fileInputStream.read(buf)) != -1) {System.out.print((new String(buf,0,readLength))); //转成char形式}} catch (IOException e) {e.printStackTrace();} finally {// 关闭流,释放资源try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}
3.FileOutputStream字节输出流

注:new FileOutputStream(filePath) 是覆盖方式 new FileOutputStream(filePath,true) 是追加方式

package com.ttc.file;import org.junit.Test;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class FileOutputStream01 {public static void main(String[] args) {}/*** 演示用FileOutputStream 将数据写入文件* 如果该文件不存在 将会自动创建文件*/@Testpublic void writeFile() {String filePath = "e:\\a.txt";// 创建 FileOutputStream对象FileOutputStream fileOutputStream = null;try {// new.FileOutputStream(filePath) 创建方式:覆盖方式  写入内容时会覆盖原来的内容// new FileOutPutStream(filePath,true) 则是追加方式 在文件末尾写入// 得到FileOutputStream流 对象// fileOutputStream = new FileOutputStream(filePath);fileOutputStream = new FileOutputStream(filePath, true);// 方法1. 写入一个字节// fileOutputStream.write('T');//方法2.  写入字符串String str = "hello world";// str.getBytes() 可以以 把字符串 转换为字节数组// fileOutputStream.write(str.getBytes());// 方法3.  FileOutputStream.write(byte[],off,length)fileOutputStream.write(str.getBytes(), 0, str.length());} catch (IOException e) {System.out.println("写入失败!");e.printStackTrace();} finally {try {System.out.println("写入成功~");fileOutputStream.close();System.out.println("关闭流");} catch (IOException e) {e.printStackTrace();System.out.println("流关闭失败");}}}
}

输入流与输出流结合

package com.ttc.file;import org.junit.Test;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class FileOutputStream01 {public static void main(String[] args) {}/*** 演示用FileOutputStream 将数据写入文件* 如果该文件不存在 将会自动创建文件*/@Testpublic void writeFile() {String filePath = "e:\\a.txt";// 创建 FileOutputStream对象FileOutputStream fileOutputStream = null;try {// new.FileOutputStream(filePath) 创建方式:覆盖方式  写入内容时会覆盖原来的内容// new FileOutPutStream(filePath,true) 则是追加方式 在文件末尾写入// 得到FileOutputStream流 对象// fileOutputStream = new FileOutputStream(filePath);fileOutputStream = new FileOutputStream(filePath, true);// 方法1. 写入一个字节// fileOutputStream.write('T');//方法2.  写入字符串String str = "hello world";// str.getBytes() 可以以 把字符串 转换为字节数组// fileOutputStream.write(str.getBytes());// 方法3.  FileOutputStream.write(byte[],off,length)fileOutputStream.write(str.getBytes(), 0, str.length());} catch (IOException e) {System.out.println("写入失败!");e.printStackTrace();} finally {try {System.out.println("写入成功~");fileOutputStream.close();System.out.println("关闭输出流");FileInputStream fileInputStream = new FileInputStream(filePath);byte[] buf = new byte[8];int fileLength = 0;while ((fileLength = fileInputStream.read(buf)) != -1) {System.out.print(new String(buf, 0, fileLength));}fileInputStream.close();System.out.println("\n关闭输入流!");} catch (IOException e) {e.printStackTrace();System.out.println("流关闭失败");}}}
}
4.文件拷贝

完成文件的拷贝 将e:\test.png 拷贝 到 d:\

  1. 创建文件输入流,将文件写入到程序
  2. 创建文件输出流,将读取到的文件数据,写入到指定的位置

注: 完成程序时,应该读取部分数据就写入到指定位置中,使用循环

package com.ttc.file;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;/*** 完成文件的拷贝*/
public class FileCopy01 {public static void main(String[] args) {
/*        1. 创建文件输入流,将文件写入到程序2. 创建文件输出流,将读取到的文件数据,写入到指定的位置注: 完成程序时,应该读取部分数据就写入到指定位置中,使用循环*/String srcFilePath = "e:\\test.png";String destFilePath = "d:\\test.png";FileInputStream fileInputStream = null;FileOutputStream fileOutputStream = null;try {fileInputStream = new FileInputStream(srcFilePath);fileOutputStream = new FileOutputStream(destFilePath);// 定义一个字节数组提高 读写效率byte[] buf = new byte[1024];int readLen = 0;while ((readLen = fileInputStream.read(buf)) != -1) {// 读取到后就写入文件 通过 FileOutputStream  实现 边读边写fileOutputStream.write(buf, 0, readLen);}System.out.println("拷贝ok~");} catch (IOException e) {e.printStackTrace();} finally {try {// 关闭输入流和输出流,释放资源if (fileInputStream != null) {fileInputStream.close();}if (fileOutputStream != null) {fileOutputStream.close();}} catch (IOException e) {e.printStackTrace();}}}
}
5.字符流
  • FileReader

    • new FileReader(File/String)
    • read:每次读取单个字符,返回该字符,读到末尾返回-1
    • read(char[]):批量读取多个字符到数组
    • 相关API: new String(char[]) new String(char[],off,len)
  • FileWriter

    • new FileWriter(File/String) 覆盖模式
    • new FileWriter(File/String,true) 追加模式
    • write(char)写入单个字符
    • write(char[])
    • write(char[],off,len)
    • write(string)
    • write(string,off,len)
    • 相关API:String类 tocharArray 将string 转换为char[]
    • 注意 FileWriter使用后 必须关闭close或者刷新flush,否则写入不到指定的文件
  • 使用FileReader读取文件

package com.ttc.file;import org.junit.Test;import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;public class FileReader_ {public static void main(String[] args) {// 1. 创建一个FileReader对象String filePath = "e:\\a.txt";FileReader fileReader = null;int data = 0;try {fileReader = new FileReader(filePath);// 循环读取 方法 1.使用read.读取单个字符while ((data = fileReader.read()) != -1) {System.out.print((char) data);}} catch (IOException e) {e.printStackTrace();} finally {try {if (fileReader != null) {fileReader.close();System.out.println("流关闭成功");}} catch (IOException e) {e.printStackTrace();}}}/*** 方法2.使用char[] 加快文件读取效率*/@Testpublic void readFile02() {String filePath = "e:\\a.txt";FileReader fileReader = null;char[] buf = new char[1024];int readLen = 0;try {fileReader = new FileReader(filePath);// 使用read(buf)返回的是实际读取的字符数 -1 表示结束while ((readLen = fileReader.read(buf)) != -1) {System.out.println(new String(buf, 0, readLen));}} catch (IOException e) {e.printStackTrace();} finally {try {fileReader.close();System.out.println("流关闭成功");} catch (IOException e) {e.printStackTrace();}}}
}
  • 使用FileWriter写文件
package com.ttc.file;import java.io.FileWriter;
import java.io.IOException;public class FileWriter_ {public static void main(String[] args) {String filePath = "e:\\note.txt";char[] chars = {'a', 'b', 'c', 'd'};// 创建FileWriterFileWriter fileWriter = null;try {fileWriter = new FileWriter(filePath); // 默认覆盖方式写入// 1.write(char) 写入单个字符fileWriter.write('H');// 2.write(char[]) 写入字符数组fileWriter.write(chars);// 3.write(char[],off,len) 写入字符数组,截取指定长度//  用String.toCharArray 可以将String转化为char[]fileWriter.write("你好哇世界".toCharArray(), 0, 3);// 4.write(string) 写入字符串fileWriter.write(" java从入门到精通");// 5.write(string,off,len) 指定字符的长度和位置fileWriter.write("我是兔兔小淘气,面对世界很好奇!!!", 0, 10);} catch (IOException e) {e.printStackTrace();} finally {// FileWriter 一定要close或者flush/*底层逻辑 写入数据的底层逻辑private void writeBytes() throws IOException {this.bb.flip();int var1 = this.bb.limit();int var2 = this.bb.position();assert var2 <= var1;int var3 = var2 <= var1 ? var1 - var2 : 0;if (var3 > 0) {if (this.ch != null) {assert this.ch.write(this.bb) == var3 : var3;} else {this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3);}}this.bb.clear();}*/if (fileWriter != null) {try {
//                    fileWriter.flush(); // 刷新// close 等价于 flush + 关闭fileWriter.close();System.out.println("输出流关闭");} catch (IOException e) {e.printStackTrace();}}}System.out.println("程序结束!!!");}
}
6.节点流和处理流

相关内容

热门资讯

触摸勇气作文 触摸勇气作文  无论在学习、工作或是生活中,大家都不可避免地要接触到作文吧,作文是一种言语活动,具有...
照妖镜作文 照妖镜作文  在日常学习、工作抑或是生活中,大家一定都接触过作文吧,借助作文人们可以实现文化交流的目...
描写清晨的作文 描写清晨的作文五篇  描写清晨的作文一  今天,我来的特别早,只见校园沉浸在一片白茫茫的大雾中,给人...
童话作文 童话作文200字三篇  导语:童话,一个熟悉而又神秘的世界,是我们童年的回忆。下面小编整理了童话作文...
名人例子经典励志故事 名人例子经典励志故事  如果可以时常之后按以下名人例子经典励志故事来看看也是挺好的,那么名人例子经典...
信心比黄金更重要哲理故事 信心比黄金更重要哲理故事  故事一般都和原始人类的生产生活有密切关系,他们迫切地希望认识自然,于是便...
山水 山水今天,爸爸公司组织去旅游,我们去了莱芜金泰山的九龙大峡谷。传说“金泰山”这一名字是泰山奶奶取得,...
养小狗的作文600字 养小狗的作文范文600字(通用7篇)  无论是在学校还是在社会中,说到作文,大家肯定都不陌生吧,根据...
描写阴天的作文 描写阴天的作文(精选70篇)  在生活、工作和学习中,大家都有写作文的经历,对作文很是熟悉吧,作文根...
向日葵作文托物言志 向日葵作文托物言志(通用57篇)  在现实生活或工作学习中,大家最不陌生的就是作文了吧,作文是人们以...
感动的作文500字 感动的作文500字感动的作文500字无声的感动在我的脑海里,有许多感人的事情发生在我的身边,在时光的...
找春天400字作文 找春天400字作文  在日常学习、工作和生活中,许多人都有过写作文的经历,对作文都不陌生吧,借助作文...
对手作文400字 关于对手作文400字(精选8篇)  在日常生活或是工作学习中,大家最不陌生的就是作文了吧,通过作文可...
与书为友作文400字 与书为友作文400字(通用26篇)  在学习、工作、生活中,大家最不陌生的就是作文了吧,借助作文可以...
感受大海作文 感受大海作文  在日复一日的学习、工作或生活中,大家都写过作文吧,根据写作命题的特点,作文可以分为命...
天使的黑白羽翼600字初中作... 天使的黑白羽翼600字初中作文  天空中,我张开了翅膀,由丑小鸭蜕变为白天鹅,而我的天使们还在原地,...
狗说明文作文500字 狗说明文作文500字(精选30篇)  在现实生活或工作学习中,大家或多或少都会接触过作文吧,作文是人...
暖优秀作文400字 暖优秀作文400字7篇  在日常学习、工作或生活中,大家或多或少都会接触过作文吧,根据写作命题的特点...
静作文150字 静作文150字第1篇静作文150字需要安静的空间,听自然 关掉电脑的音像,静静的看文章 尽管如此,马...
我不再胆小了作文350字 我不再胆小了作文350字  我是个胆小的女孩,从早到晚总是怕那些妖魔鬼怪出来一口吞了我。  记得一天...