JavaSE-19 IO

学习要点

  • File类操作文件和目录的属性
  • 字节流读写文件
  • 字符流读写文件
  • 字节流读写二进制文件

 

 

文件操作

1  文件的定义

文件可认为是相关记录或放在一起的数据的集合。文件一般保存在硬盘、U盘、光盘、云盘的媒介中。

2  Java如何操作文件

JAVA API :java.io.File 类

3  File对象构建

File file = new File( String pathname );

//String pathname格式:"e:\\test .txt"或"e:/test .txt"

  

4  File类常用方法

方法名称

说      明

boolean exists( )

判断文件或目录是否存在

boolean isFile( )

判断是否是文件

boolean isDirectory( )

判断是否是目录

String getPath( )

返回此对象表示的文件的相对路径名

String getAbsolutePath( )

返回此对象表示的文件的绝对路径名

String getName( )

返回此对象表示的文件或目录的名称

boolean delete( )

删除此对象指定的文件或目录

boolean createNewFile( )

创建名称的空文件,不创建文件夹

long  length()

返回文件的长度,单位为字节, 如果文件不存在,则返回 0L

 

 

5  File操作文件示例

public static void main(String[] args) {

        FileOperation fm = new FileOperation();

        File file = null;

        file = new File("e:\\myDoc\\test.txt");

        fm.create(file);

        fm.showFileInfo(file);

        fm.delete(file);

    }

 

    /** 创建文件的方法 */

    public void create(File file) {

        if (!file.exists()) {

            try {

                file.createNewFile();

                System.out.println("文件已创建!");

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

 

    /** 删除文件 */

    public void delete(File file) {

        if (file.exists()) {

            file.delete();

            System.out.println("文件已删除!");

        }

    }

 

    /** 显示文件信息 */

    public void showFileInfo(File file) {

        if (file.exists()) { // 判断文件是否存在

            if (file.isFile()) { // 如果是文件

                System.out.println("名称:" + file.getName());

                System.out.println("相对路径: " + file.getPath());

                System.out.println("绝对路径: " + file.getAbsolutePath());

                System.out.println("文件大小:" + file.length() + " 字节");

            }

            if (file.isDirectory()) {

                System.out.println("此文文件是目录");

            }

        } else

            System.out.println("文件不存在");

    }

 

6  上机练习

查看文件属性,创建和删除文件。

 

1  定义

Flie类提供了访问文件和目录属性的方法,如何读写文件的内容?通过流来读写。

流的概念:流是指一连串流动的字符,是以先进先出方式发送信息的通道。

  

 

输入/输出流和数据源的关系:

 

2  Java流的分类

 

 

  • 输入输出流是相对于计算机内存而言
  • 字节流是 8 位通用字节流,字符流是 16 位 Unicode 字符流
  • IO体系示意图

 

3  常用的文件读写类

文本文件的读写

字节流方式:FileInputStream、FileOutputStream

字符流方式:BufferedReader、BufferedWriter

二进制文件的读写

DataInputStream、DataOutputStream

 

字节流方式读写文本

1  FileInputStream 读文本文件

InputStream类常用方法

方法

说明

int read( )

从此输入流中读取一个数据字节。

int read(byte[] b)

从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。

int read(byte[] b,int off,int len)

从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。

void close( )

关闭此文件输入流并释放与此流有关的所有系统资源。

int available()

返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数。

 

子类FileInputStream常用的构造方法

构造方法

说明

FileInputStream(File file)

通过文件对象创建FileInputStream对象。

FileInputStream(String name)   

通过name文件路径创建FileInputStream对象。

 

示例代码

package com.etc.io;

 

//1.引入相关类

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

 

public class FISTest {

   public static void main(String[] args) {

       FileInputStream fis = null;

       try {

           // 2.构造文件输入流对象

           fis = new FileInputStream("e:\\mydoc.txt");

           // 3.读取文本文件数据

           byte[] words = new byte[1024];// 构建数组,一次读取1024个字节

           while (fis.read() > 0) {

               fis.read(words);

           }

           // 4. 输出内容

           String str = new String(words, "utf-8");

           System.out.println(str);

       } catch (FileNotFoundException e) {

           e.printStackTrace();

       } catch (IOException e) {

           e.printStackTrace();

       } finally {

           // 5. 关闭输入流

           try {

               if (fis != null) {

                   fis.close();

               }

           } catch (IOException e) {

               e.printStackTrace();

           }

       }

   }

}

  

2  FileOutputStream 写文本文件

OutputStream类常用方法

方法

说明

void write(int c)

将指定字节写入此文件输出流。

void write(byte[] buf)

将 b.length 个字节从指定 byte 数组写入此文件输出流中。

void write(byte[] b,int off,int len)

将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。

void close( )

关闭此文件输出流并释放与此流有关的所有系统资源。

 

子类FileOutputStream常用的构造方法

构造方法

说明

FileOutputStream (File file)

创建一个向指定 File 对象表示的文件中写入数据的文件输出流。

FileOutputStream(String name)  

创建一个向具有指定名称的文件中写入数据的输出文件流。

FileOutputStream(String name,

boolean append)

创建一个向指定 File 对象表示的文件中写入数据的文件输出流。如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。

注意:

1、前两种构造方法在向文件写数据时将覆盖文件中原有的内容。

2、创建FileOutputStream实例时,如果相应的文件并不存在,则会自动创建一个空的文件。

3、FileInputStream和FileOutputStream创建的流属于节点流,直接操纵数据源。

 

示例代码

package com.etc.io;

//1.引入IO相关类

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

public class FOSTest {

   public static void main(String[] args) {

       FileOutputStream fos = null;

       try {

           // 2.构造FileOutputStream对象

           fos = new FileOutputStream("e://fos.txt");

           // 3.把数据写入文本文件

           String text = "好好学习Java,天天向上!";

           byte[] words = text.getBytes();

           fos.write(words, 0, words.length);

           System.out.println("数据写入文件成功");

       } catch (FileNotFoundException e) {

           e.printStackTrace();

       } catch (IOException e) {

           e.printStackTrace();

       } finally {

           // 4.关闭文件流

           try {

               if (fos != null) {

                   fos.close();

               }

           } catch (IOException e) {

               e.printStackTrace();

           }

       }

   }

}

 

3 上机练习:复制文本文件

需求描述

文件“我的介绍.txt”位于D盘根目录下,要求将此文件的内容复制到E:\myFile\myInfo.txt中。

分析

使用FileInputStream实现读取文本文件。

使用FileOutputStream实现向文本文件中写数据

实现思路

1. 创建文件“D:\我的介绍.txt”并自行输入内容

2. 创建C:\myFile的目录。

3. 创建输入流FileInputStream对象,负责对D:\我的结束.txt文件的读取。

4. 创建输出流FileOutputStream对象,负责将文件内容写入到C:\myFile\myInfo.txt中。

5. 创建中转站数组words,存放每次读取的内容。

6. 通过循环实现文件读写。

7. 关闭输入流、输出流

 

 

 

字符流方式读写文本文件

1  BufferedReader读文本文件

使用字符流读取文本文件相关类

Reader

FileReader(节点流)

BufferedReader(处理流)

 

Reader类常用方法

int read( )

int read(char[] c)

int read(char[] c,int off,int len)

void close( )

 

子类BufferedReader常用的构造方法

public  BufferedReader(Reader in)   //in通常使用FlieReader对象

 

子类BufferedReader特有的方法

public String readLine()   //读取一行信息

 

乱码问题

方案一:字节流到字符流的转换

文本保存为utf-8格式

FileInputStream fis=new FileInputStream("e:\\mydoc.txt");

//使用InputStreamReader并设置编码格式

InputStreamReader fr=new InputStreamReader(fis,"UTF-8");

BufferedReader br=new BufferedReader(fr);

  

方案二:重构字符串

 示例代码

package com.etc.io;

//1.引入IO相关类

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class BrTest {

   public static void main(String[] args) {

       FileReader fr = null;

       BufferedReader br = null;

       try {

           // 2.创建一个FileReader对象

           fr = new FileReader("E:\\mydoc.txt");

           // 3.创建一个BufferedReader 对象

           br = new BufferedReader(fr);

           // 4.读取一行数据

           String line = br.readLine();

           while (line != null) {

               String str = new String(line.getBytes(), "UTF-8");

               System.out.println(str);

               line = br.readLine();

           }

       } catch (IOException e) {

           System.out.println("文件不存在!");

       } finally {

           try {

               // 6. 关闭 流

               if (br != null)

                   br.close();

               if (fr != null)

                   fr.close();

           } catch (IOException e) {

               e.printStackTrace();

           }

       }

   }

}

  

 

2  BufferedWriter写文本文件

使用字符流写文本文件相关类

Writer

FileWriter(节点流)

BufferedWriter(处理流)

 

Writer类常用方法

void write(String str)

void write(String str,int off,int len)

void close()

void flush()

 

子类BufferedWriter常用的构造方法

BufferedReader(Writer out)  //in通常使用FlieWriter对象

 

示例代码

package com.etc.io;

//1、引入IO相关类

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

public class BwTest {

   public static void main(String[] args) {

       FileWriter fw = null;

       BufferedWriter bw = null;

       try {

           // 2.创建一个FileWriter 对象

           fw = new FileWriter("e:\\hi.txt");

           // 3.创建一个BufferedWriter 对象

           bw = new BufferedWriter(fw);

           // 4.写入数据

           bw.write("大家好!");

           bw.write("我正在学习Java IO。");

           bw.newLine();

           bw.write("请多多指教!");

           bw.newLine();

           bw.flush();// 刷新缓冲区

           System.out.println("写入文件信息成功!");

       } catch (IOException e) {

           System.out.println("文件不存在!");

       } finally {

           // 5.关闭流

           try {

               if (bw != null) {

                   bw.close();

               }

               if (fw != null)

                   fw.close();

           } catch (IOException ex) {

               ex.printStackTrace();

           }

       }

   }

}

  

 

3  上机练习:模板文件的替换

 需求描述

1、格式模版保存在文本文件person.template中,内容如下:

您好!

我的名字是{name},我是{grade}学生。

我的专业是{speciality}。

2、其中{name}、{grade}、{speciality}是需要替换的内容,现在要求按照模板格式保存个人数据到文本文件,即把{name}、{grade}、{speciality}替换为具体的个人。

分析

1、使用Reader实现类读取文件

2、使用String的replace(char oldChar, char newChar)的方法替换内容

3、使用Writer实现类写文件

 

 

 

字节流方式读写二进制文件

1  DataInputStream类读取二进制文件(处理流)

FileInputStream的子类

与FileInputStream类结合使用读取二进制文件

2  DataOutputStream类写二进制文件(处理流)

FileOutputStream的子类

与FileOutputStream类结合使用写二进制文件

3  示例代码

/**

     * 二进制文件拷贝

     * @param sFile 源文件

     * @param dFile 目标文件

     */

    public static void copyBinFile(File sFile, File dFile) {

        FileInputStream fis = null;// 定义字节流输入节点流

        DataInputStream dis = null;// 定义二进制输入处理流

 

        FileOutputStream fos = null;// 定义字节流输出节点流

        DataOutputStream dos = null;// 定义二进制输出处理流

 

        try {

            fis = new FileInputStream(sFile);

            dis = new DataInputStream(fis);// 构建二进制输入处理流

 

            fos = new FileOutputStream(dFile);

            dos = new DataOutputStream(fos);// 构建二进制输出处理流

 

            int temp;

            while ((temp = dis.read()) != -1) {// 读取数据

                dos.write(temp);// 写数据

            }

 

            System.out.println("拷贝文件" + sFile.getName() + "成功!");

            System.out.println("文件路径:" + sFile.getAbsolutePath());

 

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            // 关闭资源

            try {

                if (dos != null) {

                    dos.close();

                }

                if (fos != null) {

                    fos.close();

                }

                if (dis != null) {

                    dis.close();

                }

                if (fis != null) {

                    fis.close();

                }

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

  

4  上机练习:从D盘拷贝一张图像文件到E盘

posted @ 2018-01-09 23:14  rask  阅读(405)  评论(0编辑  收藏  举报