Java Day8

文件的相关操作

目的

掌握文件的相关操作,理解什么是“流”和清楚I/O流。

技术

1.创建一个文件
2.向文件写入数据(字节流)
3.向文件写入数据(字符流)
4.从文件读取数据(字节流)
5.从文件读取数据(字符流)
6.向文件存一个对象
7.从文件中读取对象
8.将一个文件copy到另一个位置
9.用缓冲流copy文件

技术实现

1.创建文件

 String path ="/Users/Administrator/Desktop/Android/firstExperience/java/src/main/java/day8";
        File file = new File(path.concat("/1.txt"));

        // 判断是否存在
         if (file.exists() == false){
             // 不存在就创建
             try {
                 file.createNewFile();
             }catch (IOException e){
                 System.out.println("IO异常了");
             }

2.向文件写入数据(字节流)

// 1. 创建文件输出流对象
             FileOutputStream fos = new FileOutputStream(file);

             // 2.调用write方法写入
             byte[] text = {'1','2','3','4'};
             fos.write(text);

             // 3.操作完毕需要关闭stream对象
             fos.close();

3.向文件写入数据(字符流)

 FileWriter fw = new FileWriter(file);
             char[] name = {'安','卓','开','发'};
             fw.write(name);

             fw.close(); 

4.从文件读取数据(字节流)

  FileInputStream fis = new FileInputStream(file);

             byte[] name = new byte[8];
            int count = fis.read(name);

             fis.close();
             System.out.println(count+""+  new String(name));

5.从文件读取数据(字符流)

 FileReader fr = new FileReader(file);

             char[] book = new char[4];
             count = fr.read(book);

             fr.close();
             System.out.println(count+""+new String(book));

6.向文件存一个对象
创建一个类并序列化

import java.io.Serializable;

public class Person implements Serializable {
    public  String name ;
    public int age;
}

创建该类的一个对象并存入文件

Person xw = new Person();
        xw.name = "小王";
        xw.age = 20;

        OutputStream os = new FileOutputStream(file);

        ObjectOutputStream oos = new ObjectOutputStream(os);

        oos.writeObject(xw);
        oos.close();

7.从文件读取对象

InputStream is = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(is);
         Person xw = (Person) ois.readObject();

         System.out.println(xw.name+"  "+xw.age);

         ois.close();

8.将一个文件copy到另一个文件

 // 1.源文件的路径
        String sourcePath = "C:\\Users\\Administrator\\Desktop\\17981969_1359970249177.jpg";

        // 2.目标文件路径
        String desPath = "C:\\Users\\Administrator\\Desktop\\Android\\firstExperience\\java\\src\\main\\java\\day8\\1.jpg";

        // 3. 图片 字节
        FileInputStream fis = new FileInputStream(sourcePath);
        FileOutputStream fos = new FileOutputStream(desPath);

        byte[] in = new byte[1024];

//        while (true) {
//            int count = fis.read(in);
//            if(count != -1){
//                // 读取到内容了
//                // 将这一次读取的内容写入到目标文件
//                fos.write(in,0,count);
//            }else {
//                break;
//            }
//        }
        int count = 0;
        while ((count = fis.read(in)) != -1){
            fos.write(in,0,count);
        }


        fis.close();
        fos.close();

9.用缓冲流copy文件

String sourcePath = "C:\\Users\\Administrator\\Desktop\\17981969_1359970249177.jpg";
        String desPath = "C:\\Users\\Administrator\\Desktop\\Android\\firstExperience\\java\\src\\main\\java\\day8\\1.jpg";
        InputStream is = new FileInputStream(sourcePath);
        BufferedInputStream bis = new BufferedInputStream(is);

        OutputStream os = new FileOutputStream(desPath);
        BufferedOutputStream bos = new BufferedOutputStream(os);

        byte[] in = new byte[1024];
        int count = 0;
        while ((count = bis.read(in)) != -1){
            bos.write(in,0,count);
        }
        bis.close();
        bos.close();

技术运用

  • 密码解锁demo
    创建一个类实现文件操作部分

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

public class FileOperation {
    public static final String PATH = "C:\\Users\\Administrator\\Desktop\\Android\\firstExperience\\java\\src\\main\\java\\day8\\demo\\pwd.txt";
    String password;

    public static final FileOperation instance = new FileOperation();

    private FileOperation(){
        try {
            load();
        }catch (IOException e){
            System.out.println("io 异常");
        }
    }

    public void load() throws IOException {
        FileInputStream fis = new FileInputStream(PATH);

        byte[] pwd = new byte[4];

        int count = fis.read(pwd);

        if (count == -1){
            password = null;
        }else{
            password = new String(pwd);
        }
        fis.close();
    }

    public void save(String password){
        try {
            FileOutputStream fos = new FileOutputStream(PATH);
            fos.write(password.getBytes());
            fos.close();
        } catch (IOException e){
            System.out.println("io异常");
        }
    }
}

密码解锁

import java.util.Scanner;

public class MyClass {
    public static void main(String[] args){
        boolean logined =false;

        //判断是否已经登录
        String password = FileOperation.instance.password;
        if (password != null){
            logined = true;
        }

        //提示用户操作
        String alert;
        if (logined) {
            alert = "请输入密码";
        } else {
            alert = "请设置密码";
        }
        System.out.println(alert);

        String first = null;
        int wrongTime = 3;
        while (wrongTime >= 0) {

            //接收用户输入
            Scanner scanner = new Scanner(System.in);
            String inputPassword = scanner.next();

            //判断操作
            if (logined) {
                //已经登陆过 直接比较
                if (password.equals(inputPassword)) {
                    System.out.println("解锁成功");
                    break;
                } else {
                    if (wrongTime == 0)
                    {
                        System.out.println("密码错误次数过多,已退出!");
                        return;
                    }
                    System.out.println("解锁失败 请重新输入");
                    wrongTime--;
                }
            }else{
                //没有登陆过 在设置密码
                //判断是设置密码的第一次还是第二次
                if (first == null){
                    //第一次  保存第一次输入的密码
                    first = inputPassword;
                    System.out.println("请确认密码 ");
                }else{
                    //第二次 比较两次输入的密码是否相同
                    if (first.equals(inputPassword)){
                        System.out.println("设置密码成功");
                        //保存设置的密码
                        FileOperation.instance.save(first);
                        break;
                    }else{
                        System.out.println("两次密码不一致 请重新设置密码:");
                        first = null;
                        wrongTime--;
                    }
                }


            }
            scanner.nextLine();
        }
    }

}

运行结果
QQ图片20190814185120.png
QQ图片20190814185223.png
QQ图片20190814185304.png

心得

文件的学习虽然容易理解,但是内容还是有点杂的。感觉说不定哪天我就会把字符流和字节流记混了。还需温故而知新,这样我才能记得牢。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,904评论 1 32
  • 一、基础知识:1、JVM、JRE和JDK的区别:JVM(Java Virtual Machine):java虚拟机...
    杀小贼阅读 7,110评论 0 4
  • 五、IO流 1、IO流概述 (1)用来处理设备(硬盘,控制台,内存)间的数据。(2)java中对数据的操作都是通过...
    佘大将军阅读 3,532评论 0 0
  • 1、IO流 1.1、概述 之前学习的File类它只能操作文件或文件夹,并不能去操作文件中的数据。真正保存数据的是文...
    Villain丶Cc阅读 7,599评论 0 5
  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 11,002评论 0 9

友情链接更多精彩内容