> 文章列表 > 文件,IO流,FileInputStream,FileOutputStream,FileReader和FileWriter是字符流

文件,IO流,FileInputStream,FileOutputStream,FileReader和FileWriter是字符流

文件,IO流,FileInputStream,FileOutputStream,FileReader和FileWriter是字符流

  1. 文件就是保存数据的地方
  2. 文件流:文件在程序中是以流的形式来操作的
    1. java程序(内存)<-----输入流-----文件(磁盘,光盘等)
    2. java程序(内存)------输出流----->文件(磁盘)
    3. 流:数据在数据源(文件)和程序(内存)之间经历的路径
    4. 输入流:数据从数据源(文件)到程序(内存)的路径
    5. 输出流:数据从程序(内存)到数据源(文件)的路径
  3. 常用的文件操作
    1. package com.jshedu.file;import org.junit.jupiter.api.Test;import java.io.*;/*** @author 韩顺平* @version 1.0* 演示创建文件*/
      public class FileCreate {public static void main(String[] args) {}//方式1 new File(String pathname)@Testpublic void create01() {String filePath = "e:\\\\news1.txt";File file = new File(filePath);try {file.createNewFile();System.out.println("文件创建成功");} catch (IOException e) {e.printStackTrace();}}//方式2 new File(File parent,String child) //根据父目录文件+子路径构建//e:\\\\news2.txt@Testpublic  void create02() {File parentFile = new File("e:\\\\");String fileName = "news2.txt";//这里的file对象,在java程序中,只是一个对象//只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件File file = new File(parentFile, fileName);try {file.createNewFile();System.out.println("创建成功~");} catch (IOException e) {e.printStackTrace();}}//方式3 new File(String parent,String child) //根据父目录+子路径构建//这种方式有可能创建多个子文件比较方便@Testpublic void create03() {//String parentPath = "e:\\\\";String parentPath = "e:\\\\";String fileName = "news4.txt";File file = new File(parentPath, fileName);try {file.createNewFile();System.out.println("创建成功~");} catch (IOException e) {e.printStackTrace();}}//下面四个都是抽象类////InputStream//OutputStream//Reader //字符输入流//Writer  //字符输出流
      }
      

      创建文件的3种方法

    2. 获取文件相关信息

      package com.jshedu.file;import org.junit.jupiter.api.Test;import java.io.File;
      import java.io.IOException;/*** @author 韩顺平* @version 1.0*/
      public class FileInformation {public static void main(String[] args) {}//获取文件的信息@Testpublic void info() {//先创建文件对象File file = new File("d:\\\\news1.txt");try {file.createNewFile();//注意这个命令否则没有在磁盘创建文件} catch (IOException e) {e.printStackTrace();}//调用相应的方法,得到对应信息System.out.println("文件名字=" + file.getName());//getName、getAbsolutePath、getParent、length、exists、isFile、isDirectorySystem.out.println("文件绝对路径=" + file.getAbsolutePath());System.out.println("文件父级目录=" + file.getParent());System.out.println("文件大小(字节)=" + file.length());System.out.println("文件是否存在=" + file.exists());//TSystem.out.println("是不是一个文件=" + file.isFile());//TSystem.out.println("是不是一个目录=" + file.isDirectory());//F}
      }
      

      注意创建file.createNewFile();//注意这个命令否则没有在磁盘创建文件

    3. 目录操作

      package com.jshedu.file;import org.junit.jupiter.api.Test;import java.io.File;
      import java.io.InputStream;
      import java.io.OutputStream;/*** @author 韩顺平* @version 1.0*/
      public class Directory_ {public static void main(String[] args) {//}//判断 d:\\\\news1.txt 是否存在,如果存在就删除@Testpublic void m1() {String filePath = "e:\\\\news1.txt";File file = new File(filePath);if (file.exists()) {if (file.delete()) {System.out.println(filePath + "删除成功");} else {System.out.println(filePath + "删除失败");}} else {System.out.println("该文件不存在...");}}//判断 D:\\\\demo02 是否存在,存在就删除,否则提示不存在//这里我们需要体会到,在java编程中,目录也被当做文件@Testpublic void m2() {String filePath = "D:\\\\demo02";File file = new File(filePath);if (file.exists()) {if (file.delete()) {System.out.println(filePath + "删除成功");} else {System.out.println(filePath + "删除失败");}} else {System.out.println("该目录不存在...");}}//判断 D:\\\\demo\\\\a\\\\b\\\\c 目录是否存在,如果存在就提示已经存在,否则就创建@Testpublic void m3() {String directoryPath = "D:\\\\demo\\\\a\\\\b\\\\c";File file = new File(directoryPath);if (file.exists()) {System.out.println(directoryPath + "存在..");} else {if (file.mkdirs()) { //创建一级目录使用mkdir() ,创建多级目录使用mkdirs()System.out.println(directoryPath + "创建成功..");} else {System.out.println(directoryPath + "创建失败...");}}}
      }
      

      注意创建文件File file = new File(filePath);

  4. IO流原理及流的分类

    1. I/O是Input/Output的缩写,I/O技术用于处理数据传输。如读/写文件,网页通讯

    2. java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行

    3. java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据

    4. 抽象类不能直接实例化,流(外卖小哥)不是数据是搬运数据的交通工具,文件就相当于物品(数据)

  5.  

  6. FileInputStream:用于读取诸如图像数据的原始字节流。

    1. package com.hspedu.inputstream_;import org.junit.jupiter.api.Test;import java.io.FileInputStream;
      import java.io.FileNotFoundException;
      import java.io.IOException;/*** @author 韩顺平* @version 1.0* 演示FileInputStream的使用(字节输入流 文件--> 程序)*/
      public class FileInputStream_ {public static void main(String[] args) {}/*** 演示读取文件...* 单个字节的读取,效率比较低* -> 使用 read(byte[] b)*/@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();}}}/*** 使用 read(byte[] b) 读取文件,提高效率*/@Testpublic void readFile02() {String filePath = "e:\\\\hello.txt";//字节数组byte[] buf = new byte[8]; //一次读取8个字节.int readLen = 0;FileInputStream fileInputStream = null;try {//创建 FileInputStream 对象,用于读取 文件fileInputStream = new FileInputStream(filePath);//从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。//如果返回-1 , 表示读取完毕//如果读取正常, 返回实际读取的字节数//读入缓冲区的总字节数,如果没有更多的数据,因为文件的结尾已经到达,返回-1 。while ((readLen = fileInputStream.read(buf)) != -1) {System.out.print(new String(buf, 0, readLen));//显示}} catch (IOException e) {e.printStackTrace();} finally {//关闭文件流,释放资源.try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}
      }
      

      使用 read(byte[] b) 读取文件,提高效率,返回读取了多少字节,最后一次返回-1

  7. FileOutputStream

    package com.hspedu.outputstream_;import org.junit.jupiter.api.Test;import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;/*** @author 韩顺平* @version 1.0*/
    public class FileOutputStream01 {public static void main(String[] args) {}/*** 演示使用FileOutputStream 将数据写到文件中,* 如果该文件不存在,则创建该文件*/@Testpublic void writeFile() {//创建 FileOutputStream对象String filePath = "e:\\\\a.txt";FileOutputStream fileOutputStream = null;try {//得到 FileOutputStream对象 对象//老师说明//1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容//2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面fileOutputStream = new FileOutputStream(filePath, true);//这里和创建文件那不一样,不用单独file.createNewFile();//写入一个字节//fileOutputStream.write('H');////写入字符串String str = "hsp,world!";//str.getBytes() 可以把 字符串-> 字节数组//fileOutputStream.write(str.getBytes());/*write(byte[] b, int off, int len) 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流*/fileOutputStream.write(str.getBytes(), 0, 3);} catch (IOException e) {e.printStackTrace();} finally {try {fileOutputStream.close();//关闭流} catch (IOException e) {e.printStackTrace();}}}
    }

    写入字符串的方法,覆盖和追加的方式

  8. 在完成程序时,应该是读取部分数据,就写入指定文件

    package com.hspedu.outputstream_;import com.hspedu.inputstream_.FileInputStream_;import java.io.*;/*** @author 韩顺平* @version 1.0*/
    public class FileCopy {public static void main(String[] args) {//完成 文件拷贝,将 e:\\\\Koala.jpg 拷贝 c:\\\\//思路分析//1. 创建文件的输入流 , 将文件读入到程序//2. 创建文件的输出流, 将读取到的文件数据,写入到指定的文件.String srcFilePath = "e:\\\\Koala.jpg";String destFilePath = "e:\\\\Koala3.jpg";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();}}}
    }
    

    将文件读入java程序【输入流】,再从java程序将文件写入到指定的文件【输出流】

  9.  FileReader和FileWriter是字符流,即按照字符来操作io

  10.  FileReader的两种读取方式

    package com.jshedu.file;import org.junit.jupiter.api.Test;import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;/*** @author 韩顺平* @version 1.0*/
    public class FileReader_ {public static void main(String[] args) {}/*** 单个字符读取文件*/@Testpublic void readFile01() {String filePath = "e:\\\\story.txt";FileReader fileReader = null;int data = 0;//1. 创建FileReader对象try {fileReader = new FileReader(filePath);//循环读取 使用read, 单个字符读取while ((data = fileReader.read()) != -1) {System.out.print((char) data);}} catch (IOException e) {e.printStackTrace();} finally {try {if (fileReader != null) {fileReader.close();}} catch (IOException e) {e.printStackTrace();}}}/*** 字符数组读取文件*/@Testpublic void readFile02() {System.out.println("~~~readFile02 ~~~");String filePath = "e:\\\\story.txt";FileReader fileReader = null;int readLen = 0;char[] buf = new char[8];//1. 创建FileReader对象try {fileReader = new FileReader(filePath);//循环读取 使用read(buf), 返回的是实际读取到的字符数//如果返回-1, 说明到文件结束while ((readLen = fileReader.read(buf)) != -1) {System.out.print(new String(buf, 0, readLen));//这个位置和读取一个字符的地方不一样,String构造器,传入相应的参数//把buf数组,从0开始读取readLen这么多的字符}} catch (IOException e) {e.printStackTrace();} finally {try {if (fileReader != null) {fileReader.close();}} catch (IOException e) {e.printStackTrace();}}}}
    
  11. FileWriter案例

    package com.jshedu.file;import java.io.FileWriter;
    import java.io.IOException;/*** @author 韩顺平* @version 1.0*/
    public class FileWriter_ {public static void main(String[] args) {String filePath = "d:\\\\note.txt";//创建FileWriter对象FileWriter fileWriter = null;char[] chars = {'a', 'b', 'c'};try {fileWriter = new FileWriter(filePath);//默认是覆盖写入//注意覆盖是还在fileWriter对象基础上操作write方法参数内容更改,//在执行就把上次执行的参数内容覆盖了。//            3) write(int):写入单个字符fileWriter.write('M');//            4) write(char[]):写入指定数组fileWriter.write(chars);
    //            5) write(char[],off,len):写入指定数组的指定部分fileWriter.write("韩顺平教育".toCharArray(), 0, 3);
    //            6) write(string):写入整个字符串fileWriter.write(" 你好北京~");fileWriter.write("风雨之后,定见彩虹");
    //            7) write(string,off,len):写入字符串的指定部分fileWriter.write("上海天津", 0, 2);//在数据量大的情况下,可以使用循环操作.} catch (IOException e) {e.printStackTrace();} finally {//对应FileWriter , 一定要关闭流,或者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();}*/try {//fileWriter.flush();//关闭文件流,等价 flush() + 关闭fileWriter.close();} catch (IOException e) {e.printStackTrace();}}System.out.println("程序结束...");}
    }
    
    对应FileWriter , 一定要关闭流,或者flush才能真正的把数据写入到文件