【java高级】IO流知识点梳理-上

目录

一:File类的使用

1、File类的概述

2、File的构造器

二、通过字节流实现文本的赋值


一:File类的使用

1、File类的概述

1、java.io.File类:文件和文件目录路径的抽象表达形式,与平台无关

2、File类能够新建、删除、重命名文件和目录,但不能访问文件内容本身,如果需要访问,需要使用输入、输出流

3、想要在java中表示一个真正存在的文件和目录,则必须有一个File对象

2、File的构造器

public File(pathname)

以pathname为路径创建File对象,可以时绝对路径或相对路径

                      相对路径:是相对于某个位置开始的

                      绝对路径:是一个固定的路径,从盘符开始

public File(String parent,String child)

以parent为父路径,child为子路径创建File对象

public File(File parent,String child)

根据一个父File对象和一个子路径创建File对象

注意点:路径中的每级路径之间用一个路径分隔符分开

路径分割符和系统有关:

                   windows和DOS系统:“\”;

                      UNIX和URL:“/”;

File file1 = new File("d:\\program\\info.txt");
File file2 = new File("d:" + File.separator + "program" + File.separator + "info.txt");
File file3 = new File("d:/program");

二、通过字节流实现文本的赋值

①:通过程序获取文本内容

  public String readFileBytes(String path) {
//读取指定路径的文章内容
        byte[] b = null;
        FileInputStream fis = null;
        try {

            fis = new FileInputStream(path);
            b = new byte[fis.available()];//byte数组的长度设置为可从输入流读取的字节的总长度
            int len;
            while ((len = fis.read(b)) != -1) {//读取
                fis.read(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new String(b);

    }

②将读取到的字符串,复制到新的文件中

    public void writeFileBytes(String path, String s) {
        byte[] b = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            b = s.getBytes();//将字符串转换为byte型字节数组
            fos.write(b);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值