输入和输出处理

一.File

1.常用方法

在这里插入图片描述
Demo1类

public class Demo1 {
    public static void main(String[] args) {
        //a.txt已存在的情况下
        File file=new File("a.txt");
        //判断是否是文件
        System.out.println(file.isFile());
        //判断是否是文件夹
        System.out.println(file.isDirectory());
        //文件的名字
        System.out.println(file.getName());
        //a.txt文件里的字符长度,一个中文占三个字节
        System.out.println(file.length());
         //获取相对路径
        System.out.println(file.getPath());
        //获取绝对路径
        System.out.println(file.getAbsolutePath());
        //判断当前文件/文件夹是否存在
        System.out.println(file.exists());
        //删除文件/文件夹
        System.out.println(file.delete());
        //hello文件夹存在,test文件夹在hello里
        File file1=new File("hello/test");
        //判断是否是文件
        System.out.println(file1.isFile());
        //判断是否是文件夹
        System.out.println(file1.isDirectory());
        //文件的名字,输出文件路径的最后一级
        System.out.println(file1.getName());
        
    }
}

a.txt

I am a girl.我是女生。

控制台输出

true
false
a.txt
27
a.txt
E:\untitled3\a.txt
true
true
false
true
test

2.创建文件/文件夹

public class Demo1 {
    public static void main(String[] args) {
        //当文件不存在时,则需要创建文件
       File file=new File("aa.txt");
       //需要用try来捕获异常
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //当文件夹不存在时,则需要创建文件夹
        File file1=new File("hi");
        file1.mkdir();
        //创建多级文件夹
        File file2=new File("chen/xin/yu");
        file2.mkdirs();//递归创建文件夹
        file2.delete();//删除的是最后一级
        //创建文件和文件夹
        File file3=new File("demo/de/mo.txt");
        //获取上一级File对象,递归创建文件夹,在本级创建文件
        File file4=file3.getParentFile();
        file4.mkdirs();
        try {
            file3.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        file3.delete();//删除的是最后一级文件
    }
}

3.renameTo方法

public class Demo1 {
    public static void main(String[] args) {
        //a.txt文件夹存在
       File file=new File("a.txt");
       //d.txt文件夹不存在
       File file1=new File("d.txt");
       //把a.txt重命名为d.txt
        // renameTo方法内放变量名,且该变量对应的文件不存在
        file.renameTo(file1);
    }
}

4.练习

在这里插入图片描述

public class Demo1 {
    public static void main(String[] args) {
      File file=new File("test.txt");
        System.out.println("名称:"+file.getName());
        System.out.println("相对路径:"+file.getPath());
        System.out.println("绝对路径:"+file.getAbsolutePath());
        System.out.println("文件大小:"+file.length()+"字节");
    }
}

效果图

名称:test.txt
相对路径:test.txt
绝对路径:E:\untitled3\test.txt
文件大小:8字节

二.读/写文件

1.结构示意图

在这里插入图片描述
在这里插入图片描述

2.字节流

close遵循先开后关,后开先关原则

1)读文件(FileInputStream)

法一:

public class Demo1 {
    public static void main(String[] args) {
        FileInputStream fis=null;
        try {
            //法一:使用路径作为参数的构造
            fis=new FileInputStream("b.txt");
            int i=0;
            //使用路径把文件放入输入流中
            //如果read的值大于0或者不等于-1,则认为读到数据了
            while ((i= fis.read())!=-1){
                //把int型强转成char类型,读数据
                System.out.print((char)i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭流
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } }
}

效果图:

I am a lovely girl.

法二:

  FileInputStream fis=null;
    File file=new File("b.txt");
    try {
        //法二:使用文件对象做参数的构造方法
        fis=new FileInputStream(file);
        int i1=0;
        //建一个char数组存放字节
        char[] c=new char[fis.available()];
        int in=0;
        while ((i1=fis.read())>0){
            System.out.print(c[in] = (char) i1);
            in++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

法三:

public class Demo1 {
    public static void main(String[] args) throws Exception{
        FileInputStream fis=new FileInputStream("b.txt");
        byte[] b=new byte[fis.available()];
        fis.read(b);
        String s=new String(b);
        System.out.println(s);
    }
}

读取一部分

public class Demo1 {
    public static void main(String[] args) throws Exception{
        FileInputStream fis=new FileInputStream("b.txt");
        byte[] b=new byte[fis.available()];
        //读取从0到10
        fis.read(b,0,10);
        String s=new String(b);
        System.out.println(s);
    }
}

效果图

I am a lov 

2)写文件(FileOutputStream)

public class Demo1 {
    public static void main(String[] args) throws Exception{
        FileOutputStream fos=new FileOutputStream("d.txt");//替换写入
        String s="我要好好学习!yep!";
        byte[] b=s.getBytes();
        fos.write(b);
        System.out.println("写入完成");
    }
}

效果图

我要好好学习!yep!

加在原有内容的后面

public class Demo1 {
    public static void main(String[] args) throws Exception{
        FileOutputStream fos=new FileOutputStream("d.txt",true);//追加写入
        String s="\n"+"我要好好学习!yep!";
        byte[] b=s.getBytes();
        fos.write(b);
        System.out.println("写入完成");
    }
}

效果图

我要好好学习!yep!
我要好好学习!yep!
练习

在这里插入图片描述

public class Demo1 {
    public static void main(String[] args) throws Exception{
      FileInputStream fis=new FileInputStream("D:\\我的青春谁做主.txt");
      byte[] b=new byte[fis.available()];
        fis.read(b);
        String s=new String(b);
        System.out.println(s);
        FileOutputStream fos=new FileOutputStream("C:\\myFile\\my Prime.txt");
        fos.write(b);
        System.out.println("复制完成");
        fos.close();
        fis.close();
    }
}

效果图

我的青春我做主!yeyeye
复制完成

在这里插入图片描述

3)复制

public class Demo1 {
    public static void main(String[] args) throws Exception{
        copy("b.txt","hello\\c.txt",true);
    }
    public static void copy(String inpath,String outpath,boolean isAppend)throws Exception{
        //用String类型的一个变量接收读取的字节
        String s=reader(inpath);
        writer(outpath,isAppend,s);
    }
    public static String reader(String inpath)throws Exception{
        //判断文件是否存在
        File file=new File(inpath);
        if (!file.exists()) return null;
        //判断文件是否为空
        if (file.length()==0)return " ";
        FileInputStream fis=new FileInputStream(inpath);
        byte[] b=new byte[fis.available()];
        fis.read(b);
        String s=new String(b);
        fis.close();
        System.out.println("成功读取文件");
        return s;
    }
    public static void writer(String outpath,boolean isAppend,String writein)throws Exception{
        if (null==writein){
            System.out.println("输入不能为空,写入失败");
            return;
        }
        File file=new File(outpath);
        //判断如果文件夹是否存在,如果不存在则创建一个
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        FileOutputStream fos=new FileOutputStream(outpath);
        byte[] b=writein.getBytes();
        fos.write(b);
        fos.close();
        System.out.println("成功写入文件");
    }
}

4)递归

递归算法就是程序的自身调用
在做递归算法的时候,一定要把握住出口,也就是做递归算法必须要有一个明确的递归结束条件。

练习

5)字节流读取二进制文件

public class Demo1 {
    public static void copyDataFile(String inpath,String outpath)throws Exception{
        FileInputStream fis=new FileInputStream(inpath);
        DataInputStream dis=new DataInputStream(fis);
        byte[] b=new byte[dis.available()];
        dis.read(b);
        FileOutputStream fos=new FileOutputStream(outpath);
        DataOutputStream dos=new DataOutputStream(fos);
        dos.write(b);
        dos.close();
        fos.close();
        dis.close();
        fis.close();
    }
    public static void main(String[] args) throws Exception{
        copyDataFile("C:\\Users\\LENOVO\\Desktop\\壁纸" +
                "\\IMG_1298(20200806-232251).jpg","e.jpg");
    }
}

3.字符流

1)字符流读取(FileReader)

法一

public class Demo1 {
    public static String read(String path)throws Exception{
        FileReader fr=new FileReader(path);
        int tmp=0;
        StringBuffer sb=new StringBuffer();
        while ((tmp=fr.read())!=-1){
            sb.append((char)tmp);
        }
        fr.close();
        return sb.toString();
    }
    public static void main(String[] args) throws Exception{
        String s=new String(read("c.txt"));
        System.out.println(s);
    }
}

法二

public class Demo1 {
    public static String read(String path)throws Exception{
        FileReader fr=new FileReader(path);
        char[] c=new char[(int)new File(path).length()];
        fr.read(c);
        int i = 0;
        for (i=0; i < c.length; i++) {
            if (c[i]=='\u0000'){
                break;
            }
        }
        fr.close();
        return new String(c,0,i);
//        return  new String(c).trim();
    }
    public static void main(String[] args) throws Exception{
        String s=read("c.txt");
        System.out.println(s);
    }
}

2)字符流写入(FileWriter)

public class Demo1 {
    public static void write(String path,String text,boolean isAppend)throws Exception{
        FileWriter fw=new FileWriter(path,isAppend);
        //把字符串改成char数组
        char[] c = text.toCharArray();
        fw.write(c);
        fw.close();
        System.out.println("写入完成");
    }
    public static void main(String[] args) throws Exception{
        write("c.txt","huahudie",true);
    }
}

3)BufferedReader

public class Demo1 {
    public static String readBuffer(String path)throws Exception{
        FileReader fr=new FileReader(path);
        //缓冲流
        BufferedReader br=new BufferedReader(fr);
        String s;
        StringBuffer sb=new StringBuffer();
        while (null!=(s=br.readLine())){
            sb.append(s+"\n");
        }
        br.close();//后开先关
        fr.close();//先开后关
        return sb.toString();
    }
    public static void main(String[] args) throws Exception{
        String s=readBuffer("c.txt");
        System.out.println(s);
    }
}

4)BufferedWriter

public class Demo1 {
    public static void writeBuffer(String path,String text,boolean isAppend)throws Exception{
        FileWriter fw=new FileWriter(path,isAppend);
        BufferedWriter bw=new BufferedWriter(fw);
        bw.write(text);
        bw.close();
        fw.close();
    }
    public static void main(String[] args) throws Exception{
        writeBuffer("c.txt","hhh",true);
    }
}

5)练习

替换文本文件内容
在这里插入图片描述

public class Demo1 {
    public static String readTest(String path)throws Exception{
      FileReader fr=new FileReader(path);
      BufferedReader br=new BufferedReader(fr);
      String s;
      StringBuffer sb=new StringBuffer();
      while ((s=br.readLine())!=null){
          sb.append(s);
      }
      br.close();
      fr.close();
      return sb.toString();
    }
    public static void writeTest(String path,String text,boolean isAppend)throws Exception{
        FileWriter fw=new FileWriter(path,isAppend);
        BufferedWriter bw=new BufferedWriter(fw);
        String s=text.replace("{name}","欧欧");
        String s1=s.replace("{type}","狗狗");
        String s2=s1.replace("{master}","李伟");
        fw.write("\n"+s2);
        System.out.println("替换后:"+s2);
        bw.close();
        fw.close();
    }
    public static void main(String[] args) throws Exception{
        String s=readTest("c.txt");
        System.out.println("替换前:"+s);
        writeTest("c.txt",s,true);
    }
}

4.转换流

作用:将字节流转换成字符流

public class Demo1 {
    public static String readCharset(String path)throws Exception{
        FileInputStream fis=new FileInputStream(path);
        InputStreamReader isr=new InputStreamReader(fis,"UTF-8");  //转换字符编码
        BufferedReader br=new BufferedReader(isr);
        String s;
        StringBuffer sb=new StringBuffer();
        while ((s=br.readLine())!=null){
            sb.append(s+"\n");
        }
        br.close();
        isr.close();
        fis.close();
        return sb.toString();
    }
    public static void writeCharset(String path,String text,boolean isAppend,String charsetName)throws Exception{
        FileOutputStream fos=new FileOutputStream(path,isAppend);
        OutputStreamWriter osw=new OutputStreamWriter(fos,charsetName);
//        BufferedWriter bw=new BufferedWriter(osw);
//        bw.write(text);
//        也可以直接写
//        osw.close();
        osw.write(text);
        osw.close();
        fos.close();

    }
    public static void main(String[] args) throws Exception{
        String s=readCharset("c.txt");
        writeCharset("d.txt",s,true,"UTF-8");
        System.out.println(s);
    }
}

5.序列化和反序列化

Student类

public class Student implements Serializable {//可序列化接口
    private int id;
    private String name;
    private double score;

    public Student() {
    }

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

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", score=" + score +
                '}';
    }
}

TestObjext类

public class TestObject {
    public static void writeObject(String path,boolean isAppend,Object obj)throws Exception{
        FileOutputStream fos=new FileOutputStream(path,isAppend);
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        oos.writeObject(obj);
        oos.close();
        fos.close();
    }
    public static Object readObject(String path)throws Exception{
        FileInputStream fis=new FileInputStream(path);
        ObjectInputStream ois=new ObjectInputStream(fis);
        Object o = ois.readObject();
        ois.close();
        fis.close();
        return o;
    }
    public static void main(String[] args) throws Exception{
        Student stu=new Student(01,"陈小宇",100);
        writeObject("g.txt",true,stu);
        Object o = readObject("g.txt");
        //判断是否是Student类
        if (o instanceof Student){
            //转型
            Student s=(Student)o;
            System.out.println(o);
        }
    }
}

效果图

Student{id=1, name='陈小宇', score=100.0}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值