IO流操作

i代表:input:输入,对应的是读操作

o代表:output:输出对应的是写操作

本地磁盘-------->计算机内存读(输入)操作

计算机内存----->本地磁盘 写(输出)操作

一、 文件与文件夹

文件分类:.doc .txt .excel .ppt .pdf .jpg .mp3/4 .exe .java .html .class .dll .md .xml .properties .yml

存储数据的集合,文本文件,二进制文件

文件夹(目录):保存文件

二、File类的常用方法

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

三、创建文件夹与文件的小案例

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

public class FileDemo {
    public static void main(String[] args) throws IOException {
        File file=new File("d://hello"); //file对象-文件夹
        if(file.exists()){//判断文件夹是否存在
            File file1=new File("d://hello/abc.txt"); //file对象-文件
            if(!file1.exists()){
                boolean newFile = file1.createNewFile();//创建文件
                if(newFile){
                    System.out.println("相对路径:"+ file1.getPath());
                    System.out.println("绝对路径:"+ file1.getAbsolutePath());
                    System.out.println("文件名称:"+ file1.getName());
                    System.out.println("文件大小:"+file1.length());
                }
            }

        }else {
            file.mkdir();//创建文件夹
            System.out.println("文件夹创建成功!");
        }

    }
}

 

四、IO流

按照方向来分,分为输入流与输出流

按照读取文件的性质来分:字节流与字符流

InputStream与Reader是所有输入流的基类

OutputStream与Writer是所有输出流的基类

InputStream:是用来操作字节的,字节输入流

OutputStream:是用来操作字节的,字节输出流

Reader:是用来操作字符的,字符输入流

Writer:是用来操作字符的,字符输出流

五、字节输入流

//方式一
FileInputStream fis = new FileInputStream("d:\\hello\\abc.txt");

//方式二
File file = new File("d:\\hello\\abc.txt");
FileInputStream fis1 = new FileInputStream(file);
5.1 read读取方式一
//方式一
FileInputStream fis = new FileInputStream("d:\\hello\\abc.txt");
int read1 = fis.read();
System.out.println((char) read1);
int read2 = fis.read();
System.out.println((char) read2);
int read3 = fis.read();
System.out.println((char) read3);
fis.close();

进阶

//方式一
FileInputStream fis = new FileInputStream("d:\\hello\\abc.txt");
int data=0;
// byte [] bytes=new byte[1024];
StringBuffer str=new StringBuffer();
while ((data=fis.read())!=-1){
//System.out.println((char) data);
str.append((char)data);
}
String s = str.toString();
System.out.println("读取到的结果为:"+s);
fis.close();
5.2 read读取方式二
/方式二
FileInputStream fis = new FileInputStream("d:\\hello\\abc.txt");
//建立缓冲区
byte [] bytes=new byte[1024];
int read = fis.read(bytes); //int read代表的是读取到的字节个数
//        for (int i = 0; i < bytes.length; i++) {
//            System.out.println(bytes[i]);
//        }
String str=new String(bytes); //使用byte数组构建了一个字符串对象
System.out.println(str);

fis.close();

进阶

//方式二(优化)
FileInputStream fis=new FileInputStream("e:\\website\\hello.txt");
//缓冲区数组
byte [] bytes=new byte[1024];
//可变字符串对象
StringBuffer sb=new StringBuffer();
//通过循环去读取
//记录读取到的个数
int num=0;
while ((num=fis.read(bytes,0,bytes.length))!=-1){
    //把读取到的byte缓冲区的内容构建为一个字符串对象
    String str=new String(bytes,0,num);
    sb.append(str);
}
System.out.println("内容:"+sb.toString()); // abcdec
System.out.println("长度:"+sb.length());

read方法,无参数用int来接收,得到的是字节内容,如果使用参数,得到的是每次读取的字节个数

 

六、字节输出流

File file=new File("d:/a.txt");
FileOutputStream fos=new FileOutputStream(file,true);//true 支持追加内容
String str="hello,java! hello,io";
byte[] bytes = str.getBytes(); //把字符串转换成一个byte数组
fos.write(bytes,5,10);//从字符串的索引的第5位开始,输出10位字符
System.out.println("输出成功!");
fos.close();

七、编码方式

ASCII编码 a-z A-Z 特殊符号 128位 ,二进制编码

GBK 编码

UNICODE编码 UTF-8

GBK与UTF-8编码汉字的方式不一样

得到本地平台支持的编码格式:

String property = System.getProperty("file.encoding");
System.out.println(property);

八、复制文件案例代码

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
@author:mengshujun
@createTime: 2024-03-18 15:31:03 星期一
*/
public class Demo7 {
    public static void main(String[] args){
        try {
            copeFile("e:/website/dog.jpg","f:/mydog.jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("文件复制完成!");
    }

    public static void copeFile(String oldPath,String newPath) throws IOException {
        //文件的复制:1、输入流  2、输出流
        FileInputStream fis=new FileInputStream(oldPath);
        FileOutputStream fos=new FileOutputStream(newPath);
        //缓冲区数组
        byte [] bytes=new byte[1024];
        //定义一个每次读取字节的个数的变量
        int num=0;
        while ((num=fis.read(bytes))!=-1){
            fos.write(bytes,0,num);
        }
        fis.close();
        fos.close();

    }
}

九、字符输入流

Reader 类

InputStreamReader 类

FileReader 类

9.1 使用FileReader类读取中文字符
FileReader fr=new FileReader("d:\\hello.txt");
char [] chars=new char[1024];
fr.read(chars);
String str=new String(chars);
System.out.println(str);
9.2 使用InputStreamReader类解决中文乱码
FileInputStream fis=new FileInputStream("d:\\hello.txt");
InputStreamReader isr=new InputStreamReader(fis,"UTF-8");
char [] chars=new char[1024];
isr.read(chars);
String str=new String(chars);
System.out.println(str);
isr.close();
fis.close();

记事本的:ANSI编码就是GBK的格式。

优化

FileInputStream is = new FileInputStream("e:/website/abc.txt");
InputStreamReader isr = new InputStreamReader(is, "utf-8");
char[] chars = new char[1024]; //超出的字符能否读完
StringBuffer sb=new StringBuffer();
int count=0;
while ((count=isr.read(chars))!=-1){
    String str=new String(chars,0,count);
    sb.append(str);
}
System.out.println(sb.toString());
System.out.println(sb.toString().length());
isr.close();
is.close();
9.3 使用高效字符缓冲流BufferedReader读取文本内容

高效的字符输入流对象,特征:1、自带缓存区 2、每次读一行 3、读到的内容都为字符串

FileInputStream fis=new FileInputStream("d:\\hello.txt");
InputStreamReader isr=new InputStreamReader(fis,"UTF-8");
BufferedReader br=new BufferedReader(isr);
String str="";
StringBuffer sb=new StringBuffer();
while ((str=br.readLine())!=null){
    sb.append(str);
}
System.out.println(sb.toString());
br.close();
isr.close();
fis.close();

 操作字符串的时候,trim()方法可以去除前后的空格。replace可以替换字符串

10、序列化与反序列化

对象要序列化前提是对象必须实现一个接口Serializable,添加一个

private static final long serialVersionUID = 1L;

 

Serializable接口是启用其序列化功能的接口。实现java.io.Serializable 接口的类是可序列化的。没有实现此接口的类将不能使它们的任意状态被序列化或逆序列化。

实体类,必须要实现Serializable接口:

package cn.hxzy.entity;

import java.io.Serializable;

/**
@author:mengshujun
@createTime: 2024-03-18 17:07:05 星期一
*/
public class Student implements Serializable { //序列化接口
    private String id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
10.1 序列化操作
Student student=new Student("10086","小王",20);
//序列化-输出
//字节输出流,指定的是路径
FileOutputStream fos=new FileOutputStream("e:/student.txt");
ObjectOutputStream  oos=new ObjectOutputStream(fos);
oos.writeObject(student);
System.out.println("对象序列化完成");
oos.close();
fos.close();
10.2 反序列化操作
FileInputStream fis=new FileInputStream("e:/student.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Object object = ois.readObject();
if(object!=null){
    Student student= (Student) object;
    System.out.println(student.getId()+"=="+student.getName()+"=="+student.getAge());
}
ois.close();
fis.close();

  • 27
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值