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

一、文件操作

1. File的構(gòu)造方法

  • 允許傳入一個(gè)表示路徑的字符串,可以是絕對(duì)路徑也可以是相對(duì)路徑,內(nèi)部調(diào)用文件系統(tǒng)類的方法為File對(duì)象中的實(shí)例域初始化。
public File(String pathname)
  • 允許傳入兩個(gè)字符串,由命名可以看出必然是可以拼接的。
public File(String parent, String child);

//使用字符串拼接方法
String parent;
String child;
public File(parent.concat(child));
  • 傳入了一個(gè)File類的對(duì)象作為parent,其實(shí)在內(nèi)部還是將此parent.path的路徑值拿出來(lái)進(jìn)行拼接。
public File(File parent, String child);

2. 讀取文件的內(nèi)容(I / O流)

  • 流的方向:參考的是自己的內(nèi)存空間

  • 流 Stream: 統(tǒng)一管理數(shù)據(jù)的寫入和讀取 可以理解為一個(gè)接口


    Stream
  • 輸出流:從內(nèi)存空間將數(shù)據(jù)寫到外部設(shè)備(磁盤、硬盤、光盤)開(kāi)發(fā)者只需要關(guān)心將內(nèi)存里面的寫到流里面

  • 輸入流 :將外部數(shù)據(jù)寫到內(nèi)存中 開(kāi)發(fā)者只需要關(guān)心從流里面讀取數(shù)據(jù)


    I / O

輸出流:OutputStream 字節(jié)流 Writer字符流
輸入流:InputStream 字節(jié)流 Reader 字符流

  • I / O 流對(duì)象不屬于內(nèi)存對(duì)象 需要自己關(guān)閉
  • OutputStream和 InputStream都是抽象類 不能直接使用

字節(jié)流操作
FileOutputStream ?/ ? FileInputStream
ObjectOutputStream? / ?ObjectInputStream

字符流操作
FileWriter? /? FileReader

IO流

創(chuàng)建文件:

public class MyClass {
    public static void main(String[] args) throws IOException,ClassNotFoundException {
        //創(chuàng)建文件 完整路徑
        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){
            //不存在就創(chuàng)建
            file.createNewFile();
        }
}

向文件中寫入字節(jié)流:

         //向文件寫入數(shù)據(jù)--字節(jié)流
        //1.創(chuàng)建文件輸出流對(duì)象
        FileOutputStream fos = new FileOutputStream(file);

        //2.調(diào)用Writer方法寫入
        byte[] text = {'1','2','3','4'};
        fos.write(text);

        //3.操作完畢 需要關(guān)閉對(duì)象
        fos.close();

讀取字節(jié)流:

        //讀取數(shù)據(jù)
        FileInputStream fis = new FileInputStream(file);
        byte[] name = new byte[12];
        int count = fis.read(name);
        fis.close();
        System.out.println(count+" "+new String(name));

向文件中寫入字符流:

      //向文件寫入數(shù)據(jù)字符流
        FileWriter fw = new FileWriter(file);

        char[] name = {'安','卓','開(kāi)','發(fā)'};
        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));

保存對(duì)象:

注意:保存的對(duì)象必須實(shí)現(xiàn)Serializable接口,如果對(duì)象內(nèi)部還有屬性變量是其他類的對(duì)象,這個(gè)類也必須實(shí)現(xiàn)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;
}

向文件中保存對(duì)象:

      //創(chuàng)建Dog的一個(gè)對(duì)象
        Dog wc = new Dog();
        wc.name = "旺財(cái)";

        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();

從文件中讀取對(duì)象:

      //從文件里讀取一個(gè)對(duì)象
        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();
  • 使?BufferedInputStream和BufferedOutputStream提?讀寫的速度

        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 隨機(jī)訪問(wèn)?件 使?seek定位訪問(wèn)的位置

RandomAccessFile

密碼解鎖Demo:

main:

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

        //判斷是否已經(jīng)登錄
        String password = FileOperation.instance.password;
        if (password != null){
            logined = true;
        }

        //提示用戶操作
        String alert;
        if (logined) {
            alert = "請(qǐng)輸入密碼";
        } else {
            alert = "請(qǐng)?jiān)O(shè)置密碼";
        }
        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) {
                //已經(jīng)登陸過(guò) 直接比較
                if (password.equals(inputPassword)) {
                    System.out.println("解鎖成功");
                    break;
                } else {
                    System.out.println("解鎖失敗 請(qǐng)重新輸入");
                    wrongTime--;
                }
            }else{
                //沒(méi)有登陸過(guò) 在設(shè)置密碼
                //判斷是設(shè)置密碼的第一次還是第二次
                if (first == null){
                    //第一次  保存第一次輸入的密碼
                    first = inputPassword;
                    System.out.println("請(qǐng)確認(rèn)密碼 ");
                }else{
                    //第二次 比較兩次輸入的密碼是否相同
                    if (first.equals(inputPassword)){
                        System.out.println("設(shè)置密碼成功");
                        //保存設(shè)置的密碼
                        FileOperation.instance.save(first);
                        break;
                    }else{
                        System.out.println("兩次密碼不一致 請(qǐng)重新設(shè)置密碼:");
                        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異常");
            }
        }
}

心得體會(huì):

??Fighting!Fighting!Fighting!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容