Java 流(Stream)、文件(File)和IO操作

2019-08-15  本文已影响0人  凌云struggle

一、文件操作

1. File的构造方法

public File(String pathname)
public File(String parent, String child);

//使用字符串拼接方法
String parent;
String child;
public File(parent.concat(child));
public File(File parent, String child);

2. 读取文件的内容(I / O流)

输出流:OutputStream 字节流 Writer字符流
输入流:InputStream 字节流 Reader 字符流

字节流操作
FileOutputStream  /   FileInputStream
ObjectOutputStream  /  ObjectInputStream

字符流操作
FileWriter  /  FileReader

IO流

创建文件:

public class MyClass {
    public static void main(String[] args) throws IOException,ClassNotFoundException {
        //创建文件 完整路径
        String path = "D:\\AndroidStudioProjects\\JavaCourse\\Java\\src\\main\\java\\day8";


        //path/1.txt 拼接文件名
       File file = new File(path.concat("\\1.txt"));
       // File file = new File(path,("\\1.txt"));


        //判断是否存在
        if (file.exists() == false){
            //不存在就创建
            file.createNewFile();
        }
}

向文件中写入字节流:

         //向文件写入数据--字节流
        //1.创建文件输出流对象
        FileOutputStream fos = new FileOutputStream(file);

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

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

读取字节流:

        //读取数据
        FileInputStream fis = new FileInputStream(file);
        byte[] name = new byte[12];
        int count = fis.read(name);
        fis.close();
        System.out.println(count+" "+new String(name));

向文件中写入字符流:

      //向文件写入数据字符流
        FileWriter fw = new FileWriter(file);

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

        fw.close();

读取字符流:

       FileReader fr = new FileReader(file);
        char[] book = new char[4];
        count = fr.read(book);
        fr.close();
        System.out.println(count+" "+new String(book));

保存对象:

注意:保存的对象必须实现Serializable接口,如果对象内部还有属性变量是其他类的对象,这个类也必须实现Serializable接口

import java.io.Serializable;

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

    public Dog dog;
}

class Dog implements Serializable{
    public String name;
}

向文件中保存对象:

      //创建Dog的一个对象
        Dog wc = new Dog();
        wc.name = "旺财";

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

        OutputStream os = new FileOutputStream(file);
        ObjectOutputStream oos = new     
        ObjectOutputStream(os);
        oos.writeObject(xw);
        oos.close();

从文件中读取对象:

      //从文件里读取一个对象
        InputStream is = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(is);
        Person xw = (Person) ois.readObject();

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

        ois.close();
        long start = System.currentTimeMillis();
        String sourcePath = "C:\\Users\\gyl\\Desktop\\文件夹\\0602-tabbar\\0602-2-自定义tabbarController.mov";
        String desPath = "D:\\AndroidStudioProjects\\JavaCourse\\Java\\src\\main\\java\\day8/2.mov";

        //输入流
        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();

        long end = System.currentTimeMillis();

        System.out.println(end - start);

RandomAccessFile

密码解锁Demo:

main:

public class MyClassTest {
    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 {
                    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();
        }
    }

}

FileOperation.java

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


public class FileOperation {

        public static final String PATH = "/Users/pengxiaodong/Desktop/day1/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异常");
            }
        }
}

心得体会:

  Fighting!Fighting!Fighting!

上一篇下一篇

猜你喜欢

热点阅读