Java知识点--IO流(上)

这篇博客详细介绍了Java中关于文件和IO流的知识,从文件的基本操作如创建、删除,到IO流的原理和分类。文章重点讲解了字节输入流FileInputStream和字节输出流FileOutputStream的使用,包括如何读取和写入数据,以及如何用字节流拷贝文件。此外,还讨论了字符输入流FileReader和字符输出流FileWriter,提供读取和写入文件的实例。

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

在这里插入图片描述



一、文件

1、文件的含义

文件是保存数据的地方,比如word文档,txt文本文件,视频,图片等都是文件。

2、文件流

文件在程序中是以流的形式来操作的。
在这里插入图片描述输入流:数据从文件到程序(内存)的路径。(在程序中读取文件数据)
输出流:数据从程序(内存)到文件的路径。(在程序中将数据写入文件)


二、常用的文件操作

1、创建文件对象相关构造器和方法

相关构造器:
new File(String filePath) 根据路径创建File对象
new File(File parent,String child) 根据父目录文件+子路径创建File对象
new File(tring parent,String child) 根据父目录+子路径创建File对象
方法:
createNewFile 创建新文件

2、创建文件案例演示(三种创建方法)
import org.junit.jupiter.api.Test;

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

public class FileCreate {
   
    public static void main(String[] args) {
   

    }

    @Test
    public void create01() {
   
        String filePath = "e:\\news1.txt";
        File file = new File(filePath);
        try {
   
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
   
            e.printStackTrace();
        }
    }

    @Test
    public void create02() {
   
        File parentFile = new File("e:\\");
        String fileName = "news2.txt";
        File file = new File(parentFile, fileName);
        try {
   
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
   
            e.printStackTrace();
        }
    }

    @Test
    public void create03() {
   
        String parentPath = "e:\\";
        String fileName = "news3.txt";
        File file = new File(parentPath, fileName);
        try {
   
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
   
            e.printStackTrace();
        }
    }
}
3、获取文件相关信息的方法

“文件名字” — getName()
“文件绝对路径” — getAbsolutePath()
“文件父级目录” — getParent()
“文件大小(字节)” — length()
“文件是否存在” — exists()
“是不是一个文件” — isFile()
“是不是一个目录” — isDirectory()

4、获取文件相关信息方法案例演示
import org.junit.jupiter.api.Test;

import java.io.File;

public class FileInformation {
   
    public static void main(String[] args) {
   

    }

    @Test
    public void info(){
   
        File file = new File("e:\\news1.txt");
        System.out.println("文件名字" + file.getName());
        System.out.println("文件绝对路径" + file.getAbsolutePath());
        System.out.println("文件父级目录" + file.getParent());
        System
评论 72
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

邱崇源

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值