一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Java深入淺出說流的使用

Java深入淺出說流的使用

2021-12-29 13:13威斯布魯克.猩猩 Java教程

這篇文章主要介紹了Java深入淺出說流的使用,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

 

一、File類的使用

1.File類的一個對象,代表一個文件或一個文件目錄(俗稱:文件夾)
2.File了聲明在java.io包下
3.File類中涉及到關(guān)于文件或文件目錄的創(chuàng)建、刪除、重命名、修改時間、文件大小等方法。
并涉及到寫入或讀取文件內(nèi)容的操作。入宮需要讀取或?qū)懭胛募?nèi)容,必須使用IO流來完成。
4.后續(xù)File類的對象常會作為參數(shù)傳遞到流的構(gòu)造器中,指明讀取或?qū)懭氲?quot;終點(diǎn)"。

Java深入淺出說流的使用

 

A.常用構(gòu)造器

Java深入淺出說流的使用

 

B.路徑分隔符

Java深入淺出說流的使用

/*
    1.如何創(chuàng)建File類的實(shí)例
      File(String filePath)
      File(String parentPath,String,childPath)
      File(File parentFile,String childPath)
    2.相對路徑:相較于某個路徑下,知名的路徑。
      絕對路徑:包含盤符在內(nèi)的未見或文件目錄的路徑
    3.路徑分隔符
      windows:
      unix:/
     */
    public void test1() {
        //構(gòu)造器1
        File file1 = new File("hello.txt");//相對于module
        File file2 = new File("E:zxdymIDEAcodeJavaSenior2021_08he.txt");
        System.out.println(file1);
        System.out.println(file2);
        //構(gòu)造器2
        File file3 = new File("E:zxdymIDEAcode", "JavaSenior");
        System.out.println(file3);
        //構(gòu)造器3
        File file4 = new File(file3, "hi.txt");
        System.out.println(file4);
    }

 

C.常用方法

Java深入淺出說流的使用

Java深入淺出說流的使用

Java深入淺出說流的使用

 
    public void test2() {
        File file1 = new File("hello.txt");
        File file2 = new File("d:iohi.txt");
        System.out.println(file1.getAbsolutePath());
        System.out.println(file1.getPath());
        System.out.println(file1.getName());
        System.out.println(file1.getParent());
        System.out.println(file1.length());
        System.out.println(new Date(file1.lastModified()));
        System.out.println();
        System.out.println(file2.getAbsolutePath());
        System.out.println(file2.getPath());
        System.out.println(file2.getName());
        System.out.println(file2.getParent());
        System.out.println(file2.length());
        System.out.println(file2.lastModified());
    }
    public void test3() {
        File file = new File("E:\zxdym\IDEA\code\JavaSenior");
        String[] list = file.list();
        for (String s : list) {
            System.out.println(s);
        }
        System.out.println();
        File[] files = file.listFiles();
        for (File f : files) {
            System.out.println(f);
        }
    }
/*
    public boolean removeTo(File dest):把文件重命名為指定的文件路徑
      比如:file1.renameTo(file2)為例:
            要想保證返回true,需要file1在硬盤中是存在的,且file2不能在硬盤中存在。
     */
    @Test
    public void test4() {
        File file1 = new File("hello.txt");
        File file2 = new File("D:iohi.txt");
        boolean renameTo = file1.renameTo(file2);
        System.out.println(renameTo);
    }
 
    @Test
    public void test5() {
        File file1 = new File("hello.txt");
        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());
        System.out.println(file1.exists());
        System.out.println(file1.canRead());
        System.out.println(file1.canWrite());
        System.out.println(file1.isHidden());
    }
 @Test
    public void test6() throws IOException {
        File file1 = new File("hi.txt");
        if (!file1.exists()) {
            file1.createNewFile();
            System.out.println("創(chuàng)建成功");
        } else {//文件存在
            file1.delete();
            System.out.println("刪除成功");
        }
    }
    @Test
    public void test7(){
        //文件目錄的創(chuàng)建
        File file1 = new File("e:ioio1io3");
        boolean mkdir = file1.mkdir();
        if(mkdir){
            System.out.println("創(chuàng)建成功1");
        }
 
        File file2 = new File("e:ioio1io3");
        boolean mkdir1 = file1.mkdirs();
        if(mkdir1){
            System.out.println("創(chuàng)建成功2");
        }
    }

D.注意點(diǎn)

Java深入淺出說流的使用

 

二、流的分類及其體系

Java深入淺出說流的使用

Java深入淺出說流的使用
Java深入淺出說流的使用

開發(fā)中,用緩沖流,效率比節(jié)點(diǎn)流高(藍(lán)色框中的表示重要的、常用的)

 

輸入、輸出的標(biāo)準(zhǔn)化過程

 

1.輸入過程

A.創(chuàng)建File類的對象,指明讀取的數(shù)據(jù)的來源。(要求此文件一定要存在)

B.創(chuàng)建相應(yīng)的輸入流,將File類的對象作為參數(shù),傳入流的構(gòu)造器中

C.具體的讀入過程:

創(chuàng)建相應(yīng)的byte[] 或 char[]

D.關(guān)閉流資源

說明:程序中出現(xiàn)的異常需要使用try-catch-finally處理。

 

2.輸出過程

A.創(chuàng)建File類的對象,指明寫出的數(shù)據(jù)的來源。(要求此文件一定要存在)

B.創(chuàng)建相應(yīng)的輸出流,將File類的對象作為參數(shù),傳入流的構(gòu)造器中

C.具體的寫出過程:

write(char[]/byte[] buffer,0,len)

D.關(guān)閉流資源

說明:程序中出現(xiàn)的異常需要使用try-catch-finally處理。

public class FileReaderWriterTest {
    public static void main(String[] args) {
        File file = new File("hello.txt");//相較于前工程
        System.out.println(file.getAbsolutePath());
        File file1 = new File("2021_08hello.txt");
        System.out.println(file1.getAbsolutePath());
    }
    /*
    將day09下的hello.txt文件內(nèi)容讀入程序中,并輸出到控制臺
    說明點(diǎn):
    1.read()的理解,返回讀入的一個字符,如果達(dá)到文件末尾,返回-1
    2.異常的處理:為了保證流資源一定可以執(zhí)行關(guān)閉操作。需要使用try-catch-finally處理
    3.讀入的文件一定要存在,否則就會報FileNotFoundException.
     */
    @Test
    public void testFileReader(){
        FileReader fr = null;
        try {
            //1.實(shí)例化File類的對象,指明要操作的文件
            File file = new File("hello.txt");//相較于當(dāng)前Module
            //2.提供具體的流
            fr = new FileReader(file);
            //3.數(shù)據(jù)的讀入
            //read():返回讀入的一個字符,如果達(dá)到文件末尾,返回-1
            //方式一:
//        int data = fr.read();
//        while(data != -1){
//            System.out.print((char)data);
//            data = fr.read();
//        }
            //方式二:語法上針對方式一的修改
            int data;
            while((data = fr.read()) != -1){
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流的關(guān)閉操作
            try {
                if(fr != null)
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
    @Test
    public void testFileReader1(){
        FileReader fr = null;
        try {
            //1.File類的實(shí)例化
            File file = new File("hello.txt");
            //2.FileReader流的實(shí)例化
            fr = new FileReader(file);
            //3.讀入的操作
            //read(char[] cbuf):返回每次讀入cbuf數(shù)組中的字符的個數(shù),如果達(dá)到文件末尾,返回-1
            char[] cbuf = new char[5];
            int len;
            while(( len = fr.read(cbuf)) != -1){
                //方式一:
                //錯誤的寫法//知識點(diǎn)難點(diǎn):數(shù)組元素的覆蓋
//                for(int i = 0;i < cbuf.length;i++){
//                    System.out.print(cbuf[i]);
//                }
                //正確的寫法
//                for(int i = 0;i < len;i++){
//                    System.out.print(cbuf[i]);
//                }
                //方式二:
                //錯誤的寫法,對應(yīng)著方式一的錯誤的寫法
//                String str = new String(cbuf);
//                System.out.println(str);
                //正確的寫法
                String str = new String(cbuf, 0, len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fr != null){
            //4.資源的關(guān)閉
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
        }
    }
    /*
    從內(nèi)存中寫出數(shù)據(jù)到硬盤的文件里
    說明:
    1.輸出操作,對應(yīng)的File可以不存在的,并不會報異常
    2.
      File對應(yīng)的硬盤中的文件如果不存在,在輸出的過程中,會自動創(chuàng)建此文件
      File對應(yīng)的硬盤中的文件如果存在:
              如果流使用的構(gòu)造器是:FileWriter(file,false) / FileWriter(file):對原有文件的覆蓋
              如果流使用的構(gòu)造器是:FileWriter(file,true):不會對原有文件覆蓋,而是在原有文件基礎(chǔ)上追加內(nèi)容
     */
    @Test
    public void testFileWriter() {
        FileWriter fw = null;
        try {
            //1.提供File類的對象,指明寫出到的文件
            File file = new File("hello1.txt");
            //2.提供FileWriter的對象,用于數(shù)據(jù)的寫出
            fw = new FileWriter(file,false);
            //3.寫出的操作
            fw.write("I have a dream!
");
            fw.write("you need to have a dream!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.流資源的關(guān)閉
            if(fw != null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Test
    public void testFileReaderFileWriter(){
        FileReader fr = null;
        FileWriter fw = null;
        try {
            //1.創(chuàng)建File類的對象,指明讀入和寫出的文件
            File srcFile = new File("hello.txt");
            File destFile = new File("hello2.txt");
 
            //不能使用字符流來處理圖片等字節(jié)數(shù)據(jù)
//            File srcFile = new File("愛情與友情.jpg");
            File destFile = new File("愛情與友情1.jpg");
            //2.創(chuàng)建數(shù)據(jù)入流和輸出流的對象
            fr = new FileReader(srcFile);
            fw = new FileWriter(destFile);
            //3.數(shù)據(jù)的讀入和寫出操作
            char[] cbuf = new char[5];
            int len;//記錄每次讀入到cbuf數(shù)組中的字符的個數(shù)
            while((len = fr.read(cbuf)) != -1){
                //每次寫出len個字符
                fw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            //4.關(guān)閉流資源
//            //方式一:
//            try {
//                fw.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }finally {
//                try {
//                    fr.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
            //方式二:
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

三、流的詳細(xì)介紹

 

1.字節(jié)流和字符流

測試FileInputStream和FileOutputStream的使用
 
public class FileInputOutputStreamTest {
    //使用字節(jié)流FileInputOutputStream處理文本文件,可能出現(xiàn)亂碼
    @Test
    public void testFileInputStream(){
        FileInputStream fis = null;
        try {
            //1.造文件
            File file = new File("hello.txt");
            //2.造流
            fis = new FileInputStream(file);
            //3.讀數(shù)據(jù)
            byte[] buffer = new byte[5];
            int len;//記錄每次讀取的字節(jié)的個數(shù)
            while((len = fis.read(buffer)) != -1){
                String str = new String(buffer, 0, len);
                System.out.print(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.關(guān)閉資源
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*
    實(shí)現(xiàn)對圖片的復(fù)制操作
     */
    @Test
    public void testFileInputOutputStream(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            File srcFile = new File("愛情與友情.jpg");
            File destFile = new File("愛情與友情2.jpg");
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            //復(fù)制的過程
            byte[] buffer = new byte[5];
            int len;
            while((len = fis.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //指定路徑下文件的復(fù)制
    public void copyFile(String srcPath,String destPath){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            //復(fù)制的過程
            byte[] buffer = new byte[5];
            int len;
            while((len = fis.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Test
    public void testCopyFile(){
        long start = System.currentTimeMillis();
        String srcPath = "C:UsersAdministratorDesktop1-視頻.avi";
        String destPath = "C:UsersAdministratorDesktop2-視頻.avi";
        copyFile(srcPath,destPath);
        long end = System.currentTimeMillis();
        System.out.println("復(fù)制操作花費(fèi)的時間為:" + (end - start));
    }
}

結(jié)論:
1.對于文本文件(.txt,.java,.c,.cpp),使用字符流處理
2.對于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,...),使用字節(jié)流處理

 

2.節(jié)點(diǎn)流和處理流(重點(diǎn))

處理流之一:緩沖流的作用
1.緩沖流:
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
2.作用:提高流的讀取,寫入的速度
提高讀寫速度的原因:內(nèi)部提供了一個緩沖區(qū),默認(rèn)情況是8kb
3.處理流:就是"套接"在已有流的基礎(chǔ)上

public class BufferedTest {
    @Test
    public void BufferedStreamTest(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.造文件
            File srcFile = new File("愛情與友情.jpg");
            File destFile = new File("愛情與友情3.jpg");
            //2.造流
            //2.1造節(jié)點(diǎn)流
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            //2.2造緩沖流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //3.復(fù)制的細(xì)節(jié):讀取、寫入
            byte[] buffer = new byte[10];
            int len;
            while((len = bis.read(buffer)) != -1){
                bos.write(buffer,0,len);
//                bos.flush();//刷新緩沖區(qū)
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.資源關(guān)閉
            //要求:先關(guān)閉外層的流,再關(guān)閉內(nèi)層的流
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //說明:關(guān)閉外層流的同時,內(nèi)層流也會自動的進(jìn)行關(guān)閉,關(guān)于內(nèi)層流的關(guān)閉,可以省略
//        fos.close();
//        fis.close();
        }
 
    }
    @Test
    public void testCopyFileWithBuffered(){
        long start = System.currentTimeMillis();
        String srcPath = "C:UsersAdministratorDesktop1-視頻.avi";
        String destPath = "C:UsersAdministratorDesktop3-視頻.avi";
        copyFileWithBuffered(srcPath,destPath);
        long end = System.currentTimeMillis();
        System.out.println("復(fù)制操作花費(fèi)的時間為:" + (end - start));
    }
    //實(shí)現(xiàn)文件復(fù)制的方法
    public void copyFileWithBuffered(String srcPath,String destPath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //1.造文件
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2.造流
            //2.1造節(jié)點(diǎn)流
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            //2.2造緩沖流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            //3.復(fù)制的細(xì)節(jié):讀取、寫入
            byte[] buffer = new byte[10];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.資源關(guān)閉
            //要求:先關(guān)閉外層的流,再關(guān)閉內(nèi)層的流
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //說明:關(guān)閉外層流的同時,內(nèi)層流也會自動的進(jìn)行關(guān)閉,關(guān)于內(nèi)層流的關(guān)閉,可以省略
//        fos.close();
//        fis.close();
        }
    }
    /*
    使用BufferedReader和BufferedWriter實(shí)現(xiàn)文本文件的復(fù)制
     */
    @Test
    public void testBufferedReaderBufferedWriter(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //創(chuàng)建文件和相應(yīng)的流
            br = new BufferedReader(new FileReader(new File("dpcp.txt")));
            bw = new BufferedWriter(new FileWriter(new File("dpcp1.txt")));
            //讀寫操作
            //方式一:使用char[]數(shù)組
//            char[] cbuf = new char[1024];
//            int len;
//            while((len = br.read(cbuf)) != -1){
//                bw.write(cbuf,0,len);
//            }
            //方式二:使用String
            String data;
            while((data = br.readLine()) != null){
                //方法一:
                bw.write(data + "
");//data中不包含換行符
                //方法二:
                bw.write(data);//data中不包含換行符
                bw.newLine();//提供換行的操作
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //關(guān)閉資源
            if(bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

處理流之二:轉(zhuǎn)換流的使用(重點(diǎn))
1.轉(zhuǎn)換流:屬于字符流
InputStreamReader:將一個字節(jié)的輸入流轉(zhuǎn)換為字符的輸入流
OutputStreamWriter:將一個字符的輸出流轉(zhuǎn)換為字節(jié)的輸出流

Java深入淺出說流的使用
Java深入淺出說流的使用

2.作用:提供字節(jié)流與字符流之間的轉(zhuǎn)換
3.解碼:字節(jié)、字節(jié)數(shù)組 ---> 字符數(shù)組、字符串
編碼:字符數(shù)組、字符串---> 字節(jié)、字節(jié)數(shù)組

說明:編碼決定了解碼的方式
4.字符集

說明:文件編碼的方式(比如:GBK),決定了解析時使用的字符集(也只能是GBK)

public class InputStreamReaderTest {
    /*
    此時處理異常的話,仍然應(yīng)該使用try-catch-finally
     */
    @Test
    public void test1() throws IOException{
        FileInputStream fis = new FileInputStream("dbcp.txt");
//        InputStreamReader isr = new InputStreamReader(fis);//使用系統(tǒng)默認(rèn)的字符集
        //參數(shù)2指明了字符集,具體使用那個字符集,取決于文件dbcp.txt保存時使用的字符集
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        char[] cbuf = new char[20];
        int len;
        while((len = isr.read(cbuf)) != -1){
            String str = new String(cbuf,0,len);
            System.out.print(str);
        }
        isr.close();
    }
    /*
    此時處理異常的話,仍然應(yīng)該使用try-catch-finally
    綜合使用InputStreamReader和OutputStreamWriter
     */
    @Test
    public void test2() throws Exception{
        //1.造文件、造流
        File file1 = new File("dbcp.txt");
        File file2 = new File("dbcp_gbk.txt");
        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");
        //2.讀寫過程
        char[] cbuf = new char[20];
        int len;
        while((len = isr.read(cbuf)) != -1){
            osw.write(cbuf,0,len);
        }
        //3.關(guān)閉資源
        isr.close();
        osw.close();
    }
}

Java深入淺出說流的使用

Java深入淺出說流的使用

 

3.其他流

 

1.標(biāo)準(zhǔn)的輸入、輸出流

1.1System.in:標(biāo)準(zhǔn)的輸入流,默認(rèn)從鍵盤輸入

Java深入淺出說流的使用

System.out:標(biāo)準(zhǔn)的輸入流,默認(rèn)從控制臺輸出

1.2System類的setIn() / setOut()方式重新指定輸入和輸出的流。

修改默認(rèn)的輸入和輸出行為:

System類的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定輸入和輸出的流。

1.3練習(xí):
從鍵盤輸入字符串,要求將讀取道德整行字符串轉(zhuǎn)換成大寫輸出。然后繼續(xù)進(jìn)行輸入操作。
直至當(dāng)輸入"e"或"exit"時,退出程序
方法一:使用Scanner實(shí)現(xiàn),調(diào)用next()返回一個字符串
方法二:使用System.in實(shí)現(xiàn)。System.in ---> 轉(zhuǎn)換流 -->BufferedReader的readLine()

 public static void main(String[] args) {
        BufferedReader br = null;
        try {
            InputStreamReader isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);
            while(true){
                System.out.println("請輸入字符串:");
                String data = br.readLine();//調(diào)用此方法讀取一行數(shù)據(jù)
                if("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){//避免空指針的寫法,之前有
                    System.out.println("程序結(jié)束");
                    break;
                }
                String upperCase = data.toUpperCase();
                System.out.println(upperCase);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Java深入淺出說流的使用

Java深入淺出說流的使用

 

對象流 (重點(diǎn))

Java深入淺出說流的使用

 

對象流的使用

1.ObjectInputStream和ObjectOutputStream
2.作用:用于存儲和讀取基本數(shù)據(jù)類型或?qū)ο蟮奶幚砹鳌?br /> 3.要想一個Java對象是可序列化的,需要滿足相應(yīng)的要求。見Person.java
4.序列化機(jī)制:(重點(diǎn)!!!!)
對象序列化機(jī)制允許把內(nèi)存中的Java對象轉(zhuǎn)換成平臺無關(guān)的二進(jìn)制流,從而允許把這種二進(jìn)制流持久的保存在磁盤上,或通過網(wǎng)絡(luò)將這種
二進(jìn)制流傳輸?shù)搅硪粋€網(wǎng)絡(luò)節(jié)點(diǎn),當(dāng)其他程序獲取了這種二進(jìn)制流,就可以恢復(fù)成原來的Java對象

 
    序列化過程:將內(nèi)存中的java對象保存到磁盤中或通過網(wǎng)絡(luò)傳輸出去
    使用ObjectOutputStream實(shí)現(xiàn)
    @Test
    public void testObjectOutputStream(){
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            oos.writeObject(new String("我愛北京天安門"));
            oos.flush();//刷新操作
            oos.writeObject(new Person("王銘",23));
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos != null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    反序列化:將磁盤文件中的對象還原為內(nèi)存中的一個Java對象
    使用ObjectInputStream來實(shí)現(xiàn)
    @Test
    public void testObjectInputStream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));
            Object obj = ois.readObject();
            String str = (String) obj;
            Person p = ois.readObject();
            System.out.println(str);
            System.out.println(p);
        }catch(IOException e){
            e.printStackTrace();
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }finally {
            if(ois != null){
                ois.close;
            }
        }
    }

 

Person類

Person需要滿足如下的要求,方可序列化
1.需要實(shí)現(xiàn)接口:Serializable
2.當(dāng)前類提供一個全局常量:serialVersionUID
3.除了當(dāng)前Person類需要實(shí)現(xiàn)Serializable接口之外,還必須保證其內(nèi)部所有屬性也必須是可序列化的(默認(rèn)情況下,基本數(shù)據(jù)類型、String:本身是可序列化的)
補(bǔ)充:ObjectOutputStream 和 ObjectInputStream不能序列化static和transient修飾的成員變量
eg:輸出結(jié)果:Person{name="null",age=0,id=0,acct=null}

public class Person implements Serializable{
    public static final long serialVersionUID = 397497937034L;
    private String name;
    private int age;
    @Override
    public String toString() {
        return "Person{" +
                "name="" + name + """ +
                ", age=" + age +
                "}";
    }
    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;
    }
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Person() {
    }
}

 

對象的序列化機(jī)制

Java深入淺出說流的使用

Java深入淺出說流的使用

 

隨機(jī)存取文件流(了解)

Java深入淺出說流的使用

Java深入淺出說流的使用 Java深入淺出說流的使用

Java深入淺出說流的使用

 
 RandomAccessFile
 1.RandomAccessFile直接繼承于java.lang.Object類,實(shí)現(xiàn)了DataInput和DataOutput接口
 2.RandomAccessFile既可以作為一個輸入流,又可以作為一個輸出流
 3.如果RandomAccessFile作為輸出流時,寫出到的文件如果不存在,則在執(zhí)行過程中自動創(chuàng)建
   如果寫出到的文件存在,則會對原有文件內(nèi)容進(jìn)行覆蓋,(默認(rèn)情況下,從頭覆蓋)
 4.可以通過相關(guān)的操作,實(shí)現(xiàn)RandomAccessFile"插入"數(shù)據(jù)的效果
 
public abstract class RandomAccessFileTest {
    @Test
    public void test1(){
        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            raf1 = new RandomAccessFile(new File("愛情與友情.jpg"), "r");
            raf2 = new RandomAccessFile(new File("愛情與友情1.jpg"), "rw");
            byte[] buffer = new byte[1024];
            int len;
            while((len = raf1.read(buffer)) != -1){
                raf2.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(raf1 != null){
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(raf2 != null){
                try {
                    raf2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Test
    public void test2()throws IOException{
        RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");
        raf1.seek(3);//將指針調(diào)到角標(biāo)為3的位置
        raf1.write("xyz".getBytes());//
        raf1.close();
    }
    
    使用RandomAccessFile實(shí)現(xiàn)數(shù)據(jù)的插入效果
    
    @Test
    public void test3() throws IOException{
        RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw");
        raf1.seek(3);//將指針調(diào)到角標(biāo)為3的位置
        //保存指針3后面的所有數(shù)據(jù)到StringBuilder中
        StringBuilder builder = new StringBuilder((int) new File("hello.txt".length()));
        byte[] buffer = new byte[20];
        int len;
        while((len = raf1.read(buffer)) != -1){
            builder.append(new String(buffer,0,len));
        }
        //調(diào)回指針,寫入"xyz"
        raf1.seek(3);
        raf1.write("xyz".getBytes());
        //將StringBuilder中的數(shù)據(jù)寫入到文件中
        raf1.write(builder.toString().getBytes());
        raf1.close();
    }
}

 

Java中的NIO

Java深入淺出說流的使用

Java深入淺出說流的使用Java深入淺出說流的使用

到此這篇關(guān)于Java深入淺出說流的使用的文章就介紹到這了,更多相關(guān)Java流內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!

原文鏈接:https://blog.csdn.net/weixin_49329785/article/details/119900357

延伸 · 閱讀

精彩推薦
  • Java教程20個非常實(shí)用的Java程序代碼片段

    20個非常實(shí)用的Java程序代碼片段

    這篇文章主要為大家分享了20個非常實(shí)用的Java程序片段,對java開發(fā)項(xiàng)目有所幫助,感興趣的小伙伴們可以參考一下 ...

    lijiao5352020-04-06
  • Java教程Java8中Stream使用的一個注意事項(xiàng)

    Java8中Stream使用的一個注意事項(xiàng)

    最近在工作中發(fā)現(xiàn)了對于集合操作轉(zhuǎn)換的神器,java8新特性 stream,但在使用中遇到了一個非常重要的注意點(diǎn),所以這篇文章主要給大家介紹了關(guān)于Java8中S...

    阿杜7482021-02-04
  • Java教程xml與Java對象的轉(zhuǎn)換詳解

    xml與Java對象的轉(zhuǎn)換詳解

    這篇文章主要介紹了xml與Java對象的轉(zhuǎn)換詳解的相關(guān)資料,需要的朋友可以參考下...

    Java教程網(wǎng)2942020-09-17
  • Java教程Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決

    Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決

    這篇文章主要介紹了Java BufferWriter寫文件寫不進(jìn)去或缺失數(shù)據(jù)的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望...

    spcoder14552021-10-18
  • Java教程升級IDEA后Lombok不能使用的解決方法

    升級IDEA后Lombok不能使用的解決方法

    最近看到提示IDEA提示升級,尋思已經(jīng)有好久沒有升過級了。升級完畢重啟之后,突然發(fā)現(xiàn)好多錯誤,本文就來介紹一下如何解決,感興趣的可以了解一下...

    程序猿DD9332021-10-08
  • Java教程小米推送Java代碼

    小米推送Java代碼

    今天小編就為大家分享一篇關(guān)于小米推送Java代碼,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧...

    富貴穩(wěn)中求8032021-07-12
  • Java教程Java使用SAX解析xml的示例

    Java使用SAX解析xml的示例

    這篇文章主要介紹了Java使用SAX解析xml的示例,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下...

    大行者10067412021-08-30
  • Java教程Java實(shí)現(xiàn)搶紅包功能

    Java實(shí)現(xiàn)搶紅包功能

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)搶紅包功能,采用多線程模擬多人同時搶紅包,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙...

    littleschemer13532021-05-16
主站蜘蛛池模板: 国产极品美女在线 | 无码精品AV久久久奶水 | 2018天天弄 | 亚洲人成网站在线观看青青 | 国内精品 大秀视频 日韩精品 | 久久成人a毛片免费观看网站 | 2020国语对白露脸 | 亚洲视频1 | 倩女还魂在线观看完整版免费 | 欧美日韩免费一区二区在线观看 | 欧美草逼视频 | 久久精品99国产精品日本 | 欧美一级乱妇老太婆特黄 | 久久久久久久久女黄 | 午夜影院和视费x看 | 久久久久久免费高清电影 | 亚洲精品久久久久69影院 | 日本高清有码视频 | 边摸边吃奶边做爽gif动态图 | 天堂在线观看中文字幕 | 香蕉免费高清完整 | 日韩精品一区二区三区免费视频 | 99视频精品国在线视频艾草 | 色操网| 99ri在线视频网 | 色婷在线 | 草β好视频 | 香蕉视频在线观看网站 | 婷婷福利| free性俄罗斯护士 | 男女羞羞的视频 | 视频一区在线免费观看 | 啊皇上你好大要知画 | 小舞同人18av黄漫网站 | 强波多野结衣女教师 | 俄罗斯妈妈k8影院在线观看 | 国产精品永久免费10000 | 91成人啪国产啪永久地址 | 国产免费资源 | 特级淫片大乳女子高清视频 | 天天干夜夜玩 |