java基础-Stream(流)、File(文件)和IO

Java中的流(Stream)提供了一个统一的接口来处理输入和输出数据文件(File)提供了一种简单的方式来操作磁盘上的文件,而I/O则允许我们在Java程序中读写数据

一、流Stream

java中得stream是一种抽象概念,流可以从多种来源读取数据,包括文件、网络和内存。分为字节流和字符流

1、字节流(InputStream和OutputStream)

字节流:处理二进制数据,用于读取和写入文件

    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream("input.txt");
            outputStream = new FileOutputStream("output.txt");
            int c;

            while ((c=inputStream.read())!=-1){
                outputStream.write(c);
            }
        }finally {
            if (inputStream!=null){
                inputStream.close();
            }
            if (outputStream!=null){
                outputStream.close();
            }
        }
    }

2、字符流(Reader和Writer)

字符流:处理文本数据,读取和写入文本文件

FileReader in = new FileReader("input.txt);
FileWriter out = new FileWriter();

3、缓冲流BufferedInputStream和BufferedOutputStream

缓冲流可以提高字节流和字符流的性能,它们通常被用来缓存数据BufferedInputStreamBufferedOutputStream是Java中两个主要的缓冲流类型,它们分别用于缓存字节和字符数据

二、文件操作

java提供了许多文件操作类,其中最重要的是 java.io.File 类
这个类代表一个文件或目录的抽象路径名,可以通过它实现文件或目录的创建、删除、重命名等操作,还可以获取文件或目录的各种属性。

  • File类构造方法
File file = new File("test.txt"); // 根据路径名创建

File dir = new File("C:\\data\\temp"); // 根据路径名创建目录

File parentDir = new File("C:\\data"); // 父目录

File childFile = new File(parentDir, "test.txt"); // 根据父目录和子路径名创建
  • File类方法
file.getName(); // 获取文件名,返回 test.txt
file.getPath(); // 获取文件路径,返回 test.txt
file.getAbsolutePath(); // 获取文件的绝对路径,返回 C:\data\temp\test.txt
file.getParent(); // 获取文件的父路径,返回 C:\data\temp
file.length(); // 获取文件长度,返回文件字节数
file.lastModified(); // 获取文件最后修改时间,返回时间戳
file.exists(); // 判断文件是否存在,返回 true 或 false
file.isDirectory(); // 判断是否是目录,返回 true 或 false
file.isFile(); // 判断是否是文件,返回 true 或 false
file.canRead(); // 判断是否可读,返回 true 或 false
file.canWrite(); // 判断是否可写,返回 true 或 false
file.isHidden(); // 判断是否隐藏,返回 true 或 false


file.createNewFile(); // 创建一个新文件
dir.mkdir(); // 创建一个新目录
file.delete(); // 删除文件或目录
file.renameTo(new File("new_test.txt")); // 重命名文件或目录

java的流stream、文件file和io

一个目录其实就是一个 File 对象,它包含其他文件和文件夹

三、读取/写入一个纯文本的文件

1、选择IO流,创建IO对象
FileWriter fw =new FileWriter  
FileReader fr = new ileReader 
2、读写操作
fw.witer() // 将数据写入io流
fr.read() // 从io流中读取数据

3、关闭IO流,释放资源
fw.flose()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值