File I/O

本文详细介绍了Java中文件操作的基本方法,包括File类的使用,以及如何通过各种流(如InputStream、OutputStream、Reader和Writer)进行文件的读写。特别关注了字节流和字符流在处理文本和二进制文件时的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,操作文件或目录的属性

File对象既可表示文件,也可表示目录。在程序中,一个File对象可以代表一个文件或目录。利用它可用来对文件或目录进行基本操作。它可以查出与文件相关的信息,如名称、最后修改日期,文件大小等。
创建一个file对象的语法格式如下:

File file = new File(String pathName);

其中pathName表示所指向的文件路径名,例如:

//创建一个指向D盘根目录下test.txt文本文件的对象
File file = new File("D:\\text.txt");

需要注意的是,在 Windows操作系统中,文件路径名中的分隔符可以使用正斜杠“/”,“C:/test.txt“也可以使用反斜杠“\”,但必须写成“\”,其中第一个表示转义符,如“C:\test.txt";

file类常用的方法

方法名称说明
boolean exists()判断文件或目录是否存在
boolean isFile()判断是否是文件
boolean isDirectory()判断是否是目录
String getPath()返回此对象表示的文件的相对路径名
String getAbsolutePath()返回此对象表示的文件的绝对路径名
String getName返回此对象表示的文件或目录的名称
boolean delete删除此对象指定的文件或目录
boolean createNewFile()创建名称的空文件,不创建文件夹
long length返回文件的长度,单位为字节,若文件不存在,则返回OL

File类是如何获取文件属性的,案例:

import java.io.File;
import java.io.IOException;

public class DemoApplication {
    public static void main(String[] args)throws IOException {
        DemoApplication fm = new DemoApplication();
        File file=new File("D:\\hello.txt");
        fm.showFileInfo(file);
    }
    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("文件不存在");
        }
    }
}

运行结果:

创建文件

    /**
     * 创建文件的方法
     * @param file
     */
    public void create(File file){
        if(!file.exists()){
            try{
                file.createNewFile();
                System.out.println("文件已经创建");
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

删除文件

    /**
     * 删除文件
     * @param file
     */
    public void delete(File file){
        if(file.exists()){
            file.delete();
            System.out.println("文件已删除");
        }
    }

二,Java的流

读文件:指把文件中的数据读取到内存中;
写文件:把内存中的数据写到文件中;

  • 按照流的流向进行划分,可以分为输入流和输出流
    (1).输入流:只能从中读取数据,而不能向其中写入数据;(数据从硬盘到内存)
    InputStream和Reader作为基类;
    (2).输出流:只能向其中写入数据,而不能从中读取数据;(数据从内存到硬盘)
    OutputStream和Write作为基类
  • 按照所操作的数据单元的不同,流又可划分成字节流和字符流
    字节流操作的最小数据单元为8位的字节;
    字符流操作的最小数据单元为16位的字符;
    区分:
    字节流建议用于二进制数据(图片),而字符流用于文本,他们的用法几乎完全一样;
    (1).字节流:
    字节输入流InputStream基类
    字节输出流OutputStream基类
    (2).字符流:
    字符输入流Reader基类
    字符输出流Writer基类

三,读写文本文件

  • 使用字节流读取文本文件
    1.字节输入流InputStream类(把文件中的数据输入到内存中)
方法名称描述
int read()读取一个字节数据
int read(byte[] b)将数据读取到字节数组中
int read(byte[] b,int off,int len)从输入流中读取最多len长度的字节,保存到字节数组b中,保存的位置从off开始
void close()关闭输入流
int available()返回输入流读取的估计字节数

2.字节输入流FileInputStream类
我们通常使用InputStream的子类FileInputStream类来实现文本文件内容的读取;以下是常用的两个构造方法:

(1).FileInputStream(File file),其中file是指定文件数据源;案例如下:

File file = new File("C:/hello.txt");
FileInputStream fis= new FileInputStream(file);

(2).FileInputStream(String name),其中name是指定文件数据源,可以是路径;案例如下:

FileInputStream fis= new FileInputStream("C:/hello.txt");

3.使用FileInputStream读取文件

public class DemoApplication {
    public static void main(String[] args)throws IOException {

        FileInputStream fis= null;
        try{
            fis = new FileInputStream("D:\\hello.txt");
            int data;
            System.out.println("可读取得字节数"+fis.available());
            System.out.print("文件内容是:");
            while((data=fis.read())!=-1){
                System.out.print((char) data+"");		//如果不进行转换,则输出的是数字,因为read()方法返回整数,如果读取的是字符串则必须进行类型转换
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(fis!=null){
                    fis.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
  • 使用字节流写文本文件
    1.字节输出流OutputStream类(把内存中的数据输出到文件中)
方法名称描述
int write()写入一个字节数据
int write(byte[] buf)写入数组buf的所有字节
int write(byte[] b,int off,int len)将字节数组中从off位置开始,长度为len的字节数据输出到输出流中
void close()关闭输出流

2.字节输出流FileOutputStream类
我们通常使用OutputStream的子类FileOutputStream类来实现向文本文件写入数据;以下是常用的三个构造方法(第一种和第二种方法在向文件写数据时将覆盖文件中原有的内容):

(1).FileOutputStream(File file),其中file是指定文件数据源;案例如下:

File file = new File("C:/hello.txt");
FileOutputStream fos= new FileOutputStream(file);

(2).FileOutputStream(String name),其中name是指定文件数据源,可以是路径;案例如下:

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

(3).FileOutputStream(String name,boolean append),其中name是指定文件数据源,可以是路径;append表示是否在文件末尾添加数据,如果设置为ture,则在文件末尾添加数据;案例如下:

FileOutputStream fos= new FileOutputStream("C:/hello.txt",true);

3.使用FileOutputStream写文本文件

public class DemoApplication {
    public static void main(String[] args)throws IOException {
        FileOutputStream fos= null;
        try{
            String str="哈哈哈哈";
            byte[] words= str.getBytes();//字节数组
            //创建流对象,以追加方式写入文件
            fos= new FileOutputStream("D:\\hello.txt");
            //写入文件
            fos.write(words,0,words.length);
            System.out.println("文件已经更新完成");
        }catch (IOException e){
            System.out.println("创建文件时出错!!!");
        }finally {
            try{
                if(fos!=null){
                    fos.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
  • 使用字符流服务文本文件
    1.字符输入流Reader类(读取字符流的抽象类)
方法名称描述
int read()从输入流中读取单个字符
int read(byte[] c)从输入流中读取c.length长度的字符,保存到字符数组c中,返回实际读取的字符数
int read(char[] c,int off,int len)从输入流中读取最多len长度的字符,保存到字符数组c中,保存的位置从off开始,返回实际读取的字符长度
void close()关闭输入流

2.字符输入流FileReader类
我们通常使用Reader的子类FileReader类来实现从文本文件读取数据;
FileReader(String fileName) //其中file是指要从中读取数据的文件的名称;
案例如下:

Reader fr=new FileReader("D:\\hello.txt");

3.使用FileReader读取文件

public class DemoApplication {
    public static void main(String[] args)throws IOException {
        //创建FileReader对象
        Reader reader= null;
        StringBuffer sb=null;
        try{
            reader = new FileReader("D:\\hello.txt");
            char ch[] = new char[1024];     //创建字符数组作为中转站
            sb=new StringBuffer();
            int length= reader.read(ch);    //将字符读入数组
            //循环读取并追加字符
            while(length!=-1){
                sb.append(ch);          //追加到字符串
                length = reader.read();
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
        	System.out.println(sb);
            try{
                if(reader!=null){
                    reader.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

4.字符输入流BufferedReader类
BufferedReader 类是 Reader 类的子类,它与FileReader 类的区别在于,BufferedReader 类带有缓冲区,它可以先把一批数据读到缓冲区,接下来的读操作都是从缓冲区内获取数据,避免每次都从数据源读取数据进行字符编码转换,从而提高读取操作的效率。BufferedReader 类常用的构造方法格式如下:

BufferedReader(Reader in)

使用此构造方法创建字符输入对象如下。

Reader fr=new FileReader("C:\\myTest.txt") ;
BufferedReader br=new BufferedReader(fr);

5.使用FileReader和BufferedReader读取文本文件

public class DemoApplication {
    public static void main(String[] args)throws IOException {
        FileReader fileReader= null;
        BufferedReader bufferedReader=null;
        try{
            //创建一个FileReader对象
            fileReader = new FileReader("D:\\\\hello.txt");
            //创建一个BufferedReader对象(缓冲对象br)
            bufferedReader = new BufferedReader(fileReader);
            //读取一行数据
            String line = bufferedReader.readLine();
            while(line!=null){
                System.out.println(line);
                line=bufferedReader.readLine();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(bufferedReader!=null){
                    bufferedReader.close();
                }
                if(fileReader!=null){
                    fileReader.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
  • 使用字符流写文本文件
    1.字符输出流Writer类(向文件写入数据的字符流)
方法名称描述
write(String str)将str字符串里包含的字符输出到指定的输出流中
write(String str,int off,int len)将str字符串里从off位置开始长度为len的字符输出到输出流中
void close()关闭输出流
void flush()刷新输出流

2.字符输出流FileWriter类
我们通常使用Writer的子类FileWriter类来实现向文本文件写入数据;
FileWriter(String fileName) //其中file是指往文件中写入数据文件的名称;
案例如下:

Writer fr=new FileWriter("D:\\hello.txt");

3.使用FileWriter向文件中写入内容

public class DemoApplication {
    public static void main(String[] args)throws IOException {
        Writer fw = null;
        try{
            fw = new FileWriter("D:\\hello.txt");
            fw.write("哈哈哈哈哈哈");
            fw.flush();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(fw!=null){
                    fw.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

4.字符输出流BufferedWriter类
BufferedWriter是Writer类的子类。BufferedWriter 与BufferedReader的流方向正好相反,BufferedWriter是把一批数据写到缓冲区,当缓冲区满的时候,再把缓冲区的数据写到字符输出流中。这可以避免每次都执行物理写操作,从而提高输入/输出操作的效率。BufferedWriter 类的常用构造方法如下:

BufferedReader(Writer out)

使用此构造方法创建字符输出流对象如下。

Writer fw=new FileWriter("C:\\myTest.txt");
BufferedWriter bw=new BufferedWriter(fw);

其中,bw就是创建的使用默认大小输出缓冲区的缓冲字符输出流。

5.使用BufferedWriter和FileWriter写文本文件

public class DemoApplication {
    public static void main(String[] args)throws IOException {
        FileWriter fw = null;
        BufferedWriter bw=null;
        try{
            //创建一个FileWriter对象
            fw=new FileWriter("D:\\hello.txt");
            //创建一个BufferedWriter对象
            bw=new BufferedWriter(fw);
            //写入信息
            bw.write("你好");
            bw.write("我是张三");
            bw.newLine();
            bw.write("你是谁");
            bw.newLine();   //插入换行符
            bw.flush();     //刷新缓冲区
            bw.close();     //关闭流
            //读取文件内容
            FileReader fr=new FileReader("D:\\hello.txt");
            BufferedReader br=new BufferedReader(fr);
            String line=br.readLine();
            while(line!=null){
                System.out.println(line);
                line = br.readLine();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(bw!=null){
                    bw.close();
                }
                if(fw!=null){
                    fw.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

四,二进制文件的读写

1.使用字节流类DataInputStream读二进制文件
DataInputStream类是FileInputStream的子类,他是FileInputStream类的拓展,利用DataInputStream类读取二进制文件的实现步骤其实与用FileInputStream类读取文本文件的步骤及其相似,而且还要用到FileInputStream类。
(1).引入相关的类

import java.io.DataInputStream;
import java.io.FileInputStream;

(2).构造一个数据输入流对象

FileInputStream fis= new FileInputStream("");
DataInputStream dis = new DataInputStream(fis);

(3).利用数据输入流类的方法读取二进制文件的数据

dis.read();

(4).关闭数据输入流

dis.close();

2.使用字节流类DataOutputStream写二进制文件
DataOutputStream类是FileOutputStream的子类,他是FileOutputStream类的拓展,利用DataOutputStream类写二进制文件的实现步骤其实与用FileOutputStream类读取文本文件的步骤及其相似,而且还要用到FileOutputStream类。
(1).引入相关的类

import java.io.DataOutputStream;
import java.io.FileOutputStream;

(2).构造一个数据输出流对象

FileOutputStream fos= new FileOutputStream("");
DataOutputStream dos = new DataOutputStream(fos);

(3).利用数据输出流类的方法读取二进制文件的数据

dos.write();

(4).关闭数据输入流

dos.close();

案例:

public class DemoApplication {
    public static void main(String[] args) throws IOException {
        DataOutputStream out = null;
        DataInputStream dis = null;
        try {
            //创建输入流对象
            FileInputStream fis=new FileInputStream("");
            dis = new DataInputStream(fis);
            //创建输出流对象
            FileOutputStream fos=new FileOutputStream("");
            out = new DataOutputStream(fos);
            int temp;
            //读取文件并写入文件
            while ((temp=dis.read())!=-1){
                out.write(temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dis!=null){
                dis.close();
            }
            if (out!=null){
                out.close();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值