黑馬程序員-File

-------android培訓(xùn)java培訓(xùn)期待與您交流!----------

概述
  • 將文件或者文件夾封裝成對(duì)象。
  • 方便對(duì)文件與文件夾的屬性信息進(jìn)行操作。
  • File對(duì)象可以作為參數(shù)傳遞給流的構(gòu)造函數(shù)使用。
package com.sergio.File;

import java.io.File;

/**
 * 三種創(chuàng)建文件對(duì)象的方式
 * Created by Sergio on 2015-04-14.
 */
public class IntroductionFile {
    public static void main(String[] args) {
        consMethod();
    }

    //創(chuàng)建file對(duì)象,file對(duì)象打印為文件的目錄,是相對(duì)打印相對(duì),是絕對(duì)打印絕對(duì)
    public static void consMethod() {
        //將a.txt封裝成file對(duì)象,可以將已有的和未出現(xiàn)的文件或者文件夾封裝成對(duì)象
        File f = new File("a.txt");
        //指定目錄下的文件
        File f2 = new File("c:\\abc", "b.txt");
        //另一種寫法
        File d = new File("c:\\txt");
        File f3 = new File(d, "c.txt");
        //根據(jù)系統(tǒng)的不同使用不同的分隔符,跨平臺(tái)分隔符。相當(dāng)于c:\\abc\\a.txt
        File f4 = new File("c:" + File.separator + "abc" + File.separator + "a.txt");
    }
}
File對(duì)象功能

1.創(chuàng)建

    public static void createFile() throws IOException {
        File f1 = new File("file.txt");
        sop("創(chuàng)建新文件" + f1.createNewFile());

        //只能創(chuàng)建一級(jí)文件夾。創(chuàng)建多級(jí)文件夾為mkdirs()
        File f2 = new File("abc");
        sop("創(chuàng)建文件夾" + f2.mkdir());
    }
    public static void sop(Object o)
    {
        System.out.println(o);
    }

2.刪除文件

    //2。刪除文件
    public static void deleteFile()
    {
        File f = new File("file.txt");
        //程序退出的時(shí)候刪除文件,當(dāng)文件在操作時(shí)被刪除時(shí)會(huì)有提示,可以使用此方法在程序退出后刪除不管異常等信息
        f.deleteOnExit();
        sop("刪除文件" + f.delete());
    }
    public static void sop(Object o)
    {
        System.out.println(o);
    }

3.判斷

    //判斷文件是否可執(zhí)行、可以度、可寫等屬性
    public static void determineFile()
    {
        File f = new File("ImageHelper.java");
        sop("文件是否存在:" + f.exists());
        sop("判斷文件是否可以執(zhí)行" + f.canExecute());
        //在判斷文件對(duì)象是否是文件或者目錄時(shí),必須要先判斷該文件對(duì)象封裝的內(nèi)容是否存在,通過exists()判斷
        //sop("判斷文件是否存在:" + f.exists());
        sop("判斷是否是目錄" + f.isDirectory());
        sop("判斷是否是文件" + f.isFile());
        sop("判斷文件是否隱藏" + f.isHidden());
    }

4.獲取文件信息

    //獲取文件信息
    public static void getInfo()
    {
        File f = new File("F:\\01.jpg");
        sop("路徑" + f.getPath());//獲取路徑的信息是文件是什么位置信息(絕對(duì)或者相對(duì))獲取什么信息
        sop("絕對(duì)路徑" + f.getAbsolutePath());
        //返回的是絕對(duì)路徑中的父目錄,如果是相對(duì)路徑返回null。如果相對(duì)路徑中有上一層目錄,那么該目錄就是返回結(jié)果
        sop("本文件的上一次文件目錄" + f.getParent());
    }

5.獲取文件列表

    //獲取文件列表
    public static void getFileList() {
        //返回操作系統(tǒng)的盤符
        File[] files = File.listRoots();
        for (File f : files) {
            System.out.println(f);
        }
        //獲取c盤下的文件列表信息
        File f = new File("c:\\");
        //調(diào)用list方法的file對(duì)象必須是封裝了一個(gè)目錄,該目錄還必須存在
        String[] name = f.list();
        for (String names : name) {
            System.out.println(names);
        }
        //返回指定目錄下的過濾過的文件名字
        File dir = new File("f:\\");
        String[] arr = dir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".jpg");
            }
        });
        for (String jpgname : arr) {
            System.out.println(jpgname);
        }
        //返回指定目錄下的文件的file對(duì)象
        File dir1 = new File("f:\\");
        File[] files1 = dir.listFiles();
        for (File f1 : files1) {
            System.out.println(f1.getName() + "::" + f1.length());
        }
    }

6.遞歸列出文件列表

  • 注意:1.限定條件、2.要注意遞歸的次數(shù),盡量避免內(nèi)存溢出。
    //遞歸列出指定目錄下及目錄下的所有的文件
    public static void showDir(File dir) {
        System.out.println(dir);
        File[] files = dir.listFiles();
        for (int x = 0; x < files.length; x++) {
            if (files[x].isDirectory())
                //遞歸
                showDir(files[x]);
            else
                System.out.println(files[x]);
        }
    }

    //按層級(jí)列出目錄下的所有文件
    public static String getLevel(int level) {
        StringBuilder sb = new StringBuilder();
        sb.append("|--");
        for (int x = 0; x < level; x++) {
            sb.insert(0, "--");
        }
        return sb.toString();
    }
    public static void showdir1(File dir, int level) {
        System.out.println(getLevel(level) + dir.getName());
        level++;
        File[] files = dir.listFiles();
        for (int x = 0; x < files.length; x++) {
            if (files[x].isDirectory())
                showdir1(files[x], level);
            else
                System.out.println(getLevel(level) + files[x]);
        }
    }

7.刪除帶內(nèi)容的目錄

  • 刪除原理:Windows中,刪除目錄從里面往外刪除(先刪除文件夾里的文件在刪除文件夾)。
package com.sergio.File;

import java.io.File;

/**
 * 刪除帶內(nèi)容的目錄
 * Created by Sergio on 2015-04-19.
 */
public class RemoveDir {
    public static void main(String[] args) {
        File file = new File("e:testdir");
        removeDir(file);
    }

    //刪除帶內(nèi)容的目錄
    public static void removeDir(File dir) {
        File[] files = dir.listFiles();
        //循環(huán)刪除文件
        for (int i = 0; i < files.length; i++) {
            //判斷隱藏屬性為循環(huán)遍歷準(zhǔn)備。刪除只需要判斷目錄即可
            if (files[i].isHidden() && files[i].isDirectory())
                removeDir(files[i]);
            else
                System.out.println(files[i].toString() + "文件" + files[i].delete());
        }
        //刪除完文件后最后刪除文件夾
        System.out.println(dir + "目錄" + dir.delete());
    }
}

8.練習(xí)

  • 將指定目錄下的java文件絕對(duì)路徑,存儲(chǔ)到一個(gè)文本文件中。
package com.sergio.File;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 將指定目錄下的java文件絕對(duì)路徑,存儲(chǔ)到一個(gè)文本文件中。
 * Created by Sergio on 2015-04-19.
 */
public class JavaFileList {
    public static void main(String[] args) {
        File dir = new File("E:\\Projects\\IntellijIDEA\\okhttp-2.3.0");
        List<File> list = new ArrayList<File>();
        fileToList(dir, list);

        File file = new File(dir, "java.txt");
        writeToFile(list, file);
    }

    public static void fileToList(File dir, List<File> list) {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory())
                fileToList(file, list);
            else {
                if (file.getName().endsWith(".java"))
                    list.add(file);
            }
        }

    }

    public static void writeToFile(List<File> list, File javaListFile) {
        BufferedWriter bufw = null;
        try {
            bufw = new BufferedWriter(new FileWriter(javaListFile));
            for (File f : list) {
                //絕對(duì)路徑
                String path = f.getAbsolutePath();
                bufw.write(path);
                bufw.newLine();
                bufw.flush();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (bufw != null)
                    bufw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

Prperties集合

1.概述

  • 是hashtable的子類。
  • 具備map集合的特點(diǎn),存儲(chǔ)的鍵值對(duì)都是字符串。
  • 常用語鍵值對(duì)形式的配置文件。

2.存取

package com.sergio.Prperties;

import java.io.*;
import java.util.Properties;
import java.util.Set;

/**
 * Created by Sergio on 2015-04-19.
 */
public class IntroductionProp {
    public static void main(String[] args) {
        setAndGet();
    }

    //設(shè)置和獲取元素
    public static void setAndGet() {
        Properties prop = new Properties();
        //設(shè)置
        prop.setProperty("zhangsan", "30");
        prop.setProperty("wangwu", "21");
        System.out.println(prop.getProperty("wangwu"));
        prop.setProperty("wangwu", "35");

        //獲取
        Set<String> name = prop.stringPropertyNames();
        for (String s : name) {
            System.out.println(s + "::" + prop.getProperty(s));
        }
    }
}

3.操作存儲(chǔ)鍵值對(duì)文件

package com.sergio.Prperties;

import java.io.*;
import java.util.Properties;

/**
 * 操作鍵值存儲(chǔ)文件
 * Created by Sergio on 2015-04-20.
 */
public class ConfigProperties {
    public static void main(String[] args) {
        saveConfigFile();
        loadDemo();
    }

    //將info.txt中的鍵值數(shù)據(jù)存儲(chǔ)到集合并進(jìn)行操作
    public static void saveConfigFile() {
        BufferedReader bufr = null;
        try {
            bufr = new BufferedReader(new FileReader("info.txt"));
            String line = null;Properties prop = new Properties();

            while ((line = bufr.readLine()) != null) {
                String[] arr = line.split("=");
                prop.setProperty(arr[0], arr[1]);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufr != null)
                    bufr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //load方法原理演示
    public static void loadDemo() {
        Properties prop = new Properties();
        FileInputStream fis = null;
        //FileOutputStream fos = null;
        try {
            fis = new FileInputStream("info.txt");
            //fos = new FileOutputStream("info.txt");
            prop.load(fis);
            //改變內(nèi)存結(jié)果,跟流有關(guān),將流中的數(shù)據(jù)寫入到文件中
            prop.setProperty("mawu", "32");
            //存儲(chǔ)數(shù)據(jù)到文件中,備注信息一般不寫中文,編碼不支持,加載的數(shù)據(jù)有固定格式:鍵=值
            //prop.store(fos, "備注信息");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
//            try {
//                if (fos != null)
//                    fos.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
        prop.list(System.out);
        System.out.println(prop);
    }
}
其他流

1.打印流(PrintStream、PrinterWriter)

  • 打印流:可將各種數(shù)據(jù)類型的數(shù)據(jù)都原樣打印。
  • PrintStream:用于接收的參數(shù)類型(File對(duì)象、字符串路徑:String、字節(jié)輸出流:OutputStream)。
  • PrintWriter:用于輸出的參數(shù)類型(File對(duì)象、字符串路徑:String、字節(jié)輸出流:OutputStream、字符輸出流:Writer)。
package com.sergio.Prperties;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;

/**
 * 打印輸出流的基本功能使用
 * Created by Sergio on 2015-04-21.
 */
public class PrintStreamDemo {
    public static void main(String[] args) throws Exception{
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
        //可以傳字符跟字節(jié)流的數(shù)據(jù),也可以自動(dòng)刷新
        PrintWriter out = new PrintWriter(new FileWriter("test.txt"), true);
        String line = null;
        while ((line = bufr.readLine()) != null)
        {
            out.println(line.toUpperCase());
        }
        out.close();
        bufr.close();
    }
}

2.序列流(SequeenceInputStream)

  • 對(duì)多個(gè)流進(jìn)行合并
package com.sergio.Prperties;

import java.io.*;
import java.util.Enumeration;
import java.util.Vector;

/**
 * 合并流使用
 * Created by Sergio on 2015-04-21.
 */
public class SequenceDemo {
    public static void main(String[] args) throws Exception {
        //Vector對(duì)象只有Enumeration的功能
        Vector<FileInputStream> v = new Vector<FileInputStream>();
        v.add(new FileInputStream("1.mp3"));
        v.add(new FileInputStream("2.mp3"));
        v.add(new FileInputStream("3.mp3"));
        //獲取元素
        Enumeration<FileInputStream> en = v.elements();
        SequenceInputStream sis = new SequenceInputStream(en);
        //輸出流操作
        FileOutputStream fos = new FileOutputStream("4.mp3");
        byte[] buf = new byte[1024 * 1024 * 10];
        int len = 0;
        while ((len = sis.read()) != -1) {
            fos.write(buf, 0, len);
        }
        fos.close();
        sis.close();
    }
}

3.切割流

  • 對(duì)一個(gè)流進(jìn)行分割
package com.sergio.Prperties;

import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;

/**
 * 切割流和合并流
 * Created by Sergio on 2015-04-21.
 */
public class SplitFile {
    public static void main(String[] args) throws Exception {
        splitFile();
        mergeFile();
    }

    //拆分文件
    public static void splitFile() throws IOException {
        FileInputStream fis = new FileInputStream("4.mp3");
        FileOutputStream fos = null;
        byte[] buf = new byte[1024 * 1024];
        int len = 0;
        int count = 1;
        while ((len = fis.read(buf)) != -1) {
            fos = new FileOutputStream((count++) + ".part");
            fos.write(buf, 0, len);
            fos.close();
        }
        fis.close();
    }

    //合并文件
    public static void mergeFile() throws IOException {
        ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
        //4個(gè)分拆文件
        for (int x = 1; x <= 4; x++) {
            al.add(new FileInputStream(x + ".part"));
        }
        final Iterator<FileInputStream> it = al.iterator();
        Enumeration<FileInputStream> en = new Enumeration<FileInputStream>() {
            @Override
            public boolean hasMoreElements() {
                return it.hasNext();
            }

            @Override
            public FileInputStream nextElement() {
                return it.next();
            }
        };
        SequenceInputStream sis = new SequenceInputStream(en);
        FileOutputStream fos = new FileOutputStream("test.mp3");
        byte[] buf = new byte[1024 * 1024 * 5];
        int len = 0;
        while ((len = sis.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        fos.close();
        sis.close();
    }
}

4.對(duì)象流

  • ObjectInputStream與ObjectOutputStream:可以操作對(duì)象。
  • 將堆內(nèi)存中的對(duì)象數(shù)據(jù)存儲(chǔ)到硬盤上,需要用到的時(shí)候再?gòu)挠脖P上讀取即可。此種操作方式為對(duì)象的序列化或者對(duì)象的持久化。
  • 被操作的對(duì)象需要實(shí)現(xiàn)Serializable(標(biāo)記接口(一般沒有方法))。
  • 靜態(tài)變量不能被序列化。
package com.sergio.IOOther;

import java.io.Serializable;

/**
 * 被序列化對(duì)象類
 * Created by Sergio on 2015-04-23.
 */
public class Person implements Serializable {
    public static final long serialVersionUID = 42L;

    String name;
    //關(guān)鍵字transient標(biāo)記age變量不能被序列化
    transient int age;
    //靜態(tài)變量不能被序列化
    static String country = "cn";

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {

        return name;
    }

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

package com.sergio.IOOther;

import java.io.*;

/**
 * 對(duì)象流操作動(dòng)作
 * Created by Sergio on 2015-04-23.
 */
public class ObjectStreamDemo {
    public static void main(String[] args) throws Exception {
        //writeObject();
        readObject();
    }

    //序列化寫入
    public static void writeObject() throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));
        oos.writeObject(new Person("lisi", 24));
        oos.close();
    }

    //序列化讀取
    public static void readObject() throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
        Person p = (Person) ois.readObject();
        System.out.println(p);
        ois.close();
    }
}

5.管道流

  • PipedInputStream和PipedOutputStream。輸入輸出可以直接進(jìn)行連接,通過結(jié)合線程使用(不建議使用單線程,容易死鎖)。
  • 作用:將輸入輸出流對(duì)接在一起使用。
package com.sergio.IOOther;

import com.sergio.lianxi.ExceptionDemo;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 管道流操作方式方法
 * Created by Sergio on 2015-04-23.
 */
public class PipedStreamDemo {
    public static void main(String[] args) throws IOException {
        PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream();
        pis.connect(pos);
        Read r = new Read(pis);
        Write w = new Write(pos);
        new Thread(r).start();
        new Thread(w).start();
    }
}


//讀取線程
class Read implements Runnable {
    private PipedInputStream in;

    Read(PipedInputStream in) {
        this.in = in;
    }

    @Override
    public void run() {
        try {
            byte[] buf = new byte[1024];
            int len = in.read(buf);
            String s = new String(buf, 0, len);
            System.out.println(s);
            in.close();
        } catch (IOException e) {
            throw new RuntimeException("管道讀取流失敗");

        }
    }
}


//寫入線程
class Write implements Runnable {
    private PipedOutputStream out;

    Write(PipedOutputStream out) {
        this.out = out;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(6000);
            out.write("管道流線程測(cè)試".getBytes());
        } catch (Exception e) {
            throw new RuntimeException("管道寫入失敗");
        }
    }
}

6.RandomAccessFile

  • 具備隨機(jī)訪問文件功能,自身具備讀寫的方法。
  • 該類不算是IO體系中的子類,而是直接繼承之Object。但是它是IO包中的成員,因?yàn)榫邆渥x和寫的功能。
  • 方法的實(shí)現(xiàn):內(nèi)部封裝了一個(gè)數(shù)組,通過指針對(duì)數(shù)組的元素進(jìn)行操作,可以通過getFilePointer獲取指針位置,同時(shí)可以通過seek改變指針的位置。
  • 讀寫原理:內(nèi)部封裝了字節(jié)輸入流和輸出流。
  • 缺點(diǎn):從構(gòu)造函數(shù)看只能操作文件。而且操作文件還有模式規(guī)定:r,rw,rws,rwd四種。
  • 注意:此對(duì)象的構(gòu)造函數(shù)藥操作的文件不存在,會(huì)自動(dòng)創(chuàng)建,如果存在會(huì)覆蓋。如果模式為只讀r,不會(huì)創(chuàng)建文件,會(huì)去讀取一個(gè)已存在的文件,如果該文件不存在,則會(huì)出現(xiàn)異常。如果模式為rw,操作的文件不存在,會(huì)自動(dòng)創(chuàng)建,如果存在則不會(huì)覆蓋。
package com.sergio.IOOther;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 隨機(jī)訪問文件
 * Created by Sergio on 2015-04-24.
 */
public class RandomAccessFileDemo {
    public static void main(String[] args) throws Exception {
        writeFile();
        writeFile_2();
        readFile();
    }

    public static void writeFile() throws Exception {
        RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
        //寫入一個(gè)字節(jié)數(shù)值
        raf.write("wangwu".getBytes());
        raf.write(23);
        //寫入32位數(shù)值
        raf.writeInt(234);
        raf.close();
    }

    public static void writeFile_2() throws Exception {
        RandomAccessFile raf = new RandomAccessFile("test.txt", "r");
        //跳過8位開始寫入數(shù)據(jù)
        raf.seek(8 * 0);
        raf.write("maliu".getBytes());
        raf.writeInt(234);
        raf.close();
    }

    public static void readFile() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("test.txt", "r");
        //調(diào)整對(duì)象中的指針,從第八個(gè)字節(jié)處取數(shù)據(jù),可以自由位置獲取
        raf.seek(8);
        //跳過指定的字節(jié)數(shù),只能向前走,不能往后跳
        //raf.skipBytes(8);
        byte[] buf = new byte[4];
        raf.read(buf);
        //獲取文件中的姓名跟年齡數(shù)據(jù)
        String name = new String(buf);
        int age = raf.readInt();
        System.out.println("name" + name);
        System.out.println("age" + age);
        raf.close();
    }
}

7.基本數(shù)據(jù)類型流

  • DataInputStream和DataOutputStream
package com.sergio.IOOther;

import java.io.*;

/**
 * 操作基本數(shù)據(jù)類型的流對(duì)象
 * Created by Sergio on 2015-05-12.
 */
public class DataStreamDemo {
    public static void main(String[] args) throws IOException {
        writeUTFDemo();
        readUTFDemo();
        readData();
        writeData();
    }

    //特殊UTF-8編碼對(duì)應(yīng)的讀取方式
    public static void readUTFDemo() throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("utfdata.txt"));
        String s = dis.readUTF();
        System.out.println(s);
        dis.close();
    }

    //特殊版UTF-8編碼寫入數(shù)據(jù)
    public static void writeUTFDemo() throws IOException {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("utfdata.txt"));
        dos.writeUTF("你好");
        dos.close();
    }

    //讀取數(shù)據(jù)
    public static void readData() throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
        int num = dis.readInt();
        boolean b = dis.readBoolean();
        double d = dis.readDouble();

        System.out.println("num" + num);
        System.out.println("b" + b);
        System.out.println("d" + d);
        dis.close();
    }

    //寫入數(shù)據(jù)
    public static void writeData() throws IOException {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        dos.writeInt(23);
        dos.writeBoolean(true);
        dos.writeDouble(238.34);
        dos.close();
    }
}

8.ByteArrayStream流

  • 操作字節(jié)數(shù)組的流對(duì)象。
  • ByteArrayInputStream:在構(gòu)造的時(shí)候,需要接受數(shù)據(jù)源,而且數(shù)據(jù)源是一個(gè)字節(jié)數(shù)組。
  • ByteArrayOutputStream:在構(gòu)造的時(shí)候,不用定義數(shù)據(jù)目的,因?yàn)樵搶?duì)象中已經(jīng)內(nèi)部封裝了可變長(zhǎng)度的字節(jié)數(shù)組,緩沖區(qū)會(huì)隨著數(shù)據(jù)的不斷寫入而自動(dòng)增長(zhǎng),這就是數(shù)據(jù)目的地。
  • 特點(diǎn):這兩個(gè)流對(duì)象都不需要進(jìn)行關(guān)閉,因?yàn)椴僮鞯氖菙?shù)組,而不是系統(tǒng)資源,可以繼續(xù)被調(diào)用,不會(huì)產(chǎn)生任何IO異常。
  • InputStreamReader和OutputStreamWriter:兩個(gè)轉(zhuǎn)換流構(gòu)造的時(shí)候加入了字符集。
package com.sergio.IOOther;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * 用流的讀寫四項(xiàng)來操作數(shù)組
 * Created by Sergio on 2015-05-13.
 */
public class ByteArrayInputStreamDemo {
    public static void main(String[] args) {
        //數(shù)據(jù)源
        ByteArrayInputStream bis = new ByteArrayInputStream("abc".getBytes());
        //數(shù)據(jù)目的
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int b = 0;
        while ((b = bis.read()) != -1) {
            bos.write(b);
        }
        System.out.println(bos.size());
        System.out.println(bos.toString());
    }
}
轉(zhuǎn)換流的字符編碼
  • 因?yàn)橛?jì)算機(jī)智能識(shí)別二進(jìn)制數(shù)據(jù),為了方便應(yīng)用計(jì)算機(jī)就將各個(gè)國(guó)家的文字用數(shù)字表示,并一一對(duì)應(yīng),形成了一張編碼表。
  • 常見編碼表:ASCII(美國(guó)標(biāo)準(zhǔn)信息交換碼)、ISO8859-1(拉丁碼表)、GB2312(中國(guó)的中文編碼表)、GBK(中文編碼的升級(jí)版,融合了更多的中文字符號(hào))、Unicode(國(guó)際標(biāo)準(zhǔn)碼,所有文字都用兩個(gè)字節(jié)表示,Java語言用就是這個(gè))、UTF-8(最多三個(gè)字節(jié)來表示一個(gè)字符)。
package com.sergio.IOOther;

import java.io.*;

/**
 * 字符編碼簡(jiǎn)單介紹
 * Created by Sergio on 2015-05-13.
 */
public class EncodeStream {
    public static void main(String[] args) throws IOException {
        writeText();
        readText();
    }

    //指定解碼的編碼表.解碼要跟編碼相同才可解碼準(zhǔn)確。
    public static void readText() throws IOException {
        //轉(zhuǎn)換流
        InputStreamReader isr = new InputStreamReader(new FileInputStream("utf.txt"), "UTF-8");
        char[] buf = new char[10];
        int len = isr.read(buf);
        String s = new String(buf, 0, len);
        System.out.println(s);
    }

    //指定編碼的編碼表
    public static void writeText() throws IOException {
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("utf.txt"), "UTF-8");
        osw.write("測(cè)試");
        osw.close();
    }
}

字符編碼
  • 編碼:字符串變字節(jié)數(shù)組。str.getBytes();
  • 解碼:字節(jié)數(shù)組變字符串。new String(byte[])
package com.sergio.IOOther;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * 編碼示例
 * Created by Sergio on 2015-05-13.
 */
public class EncodeDemo {
    public static void main(String[] args) throws Exception {
        String s = "你好!";
        //編碼
        byte[] b1 = s.getBytes("GBK");
        System.out.println(Arrays.toString(b1));
        //解碼
        String s1 = new String(b1, "GBK");
        System.out.println("s1 = " + s1);
    }

    //亂碼演示和解決
    public static void encodeDemo() throws UnsupportedEncodingException {
        String s = "測(cè)試";
        //使用GBK編碼
        byte[] b = s.getBytes("GBK");
        //使用ISO8859-1進(jìn)行解碼,就會(huì)發(fā)生亂碼
        String s1 = new String(b, "ISO-8859-1");
        System.out.println(s1);

        //對(duì)以上亂碼解決方式如下。先獲得編解碼的字節(jié)碼數(shù)組,然后再對(duì)字節(jié)數(shù)組進(jìn)行正確的編碼和解碼,通用方法
        //注意:當(dāng)?shù)谝淮尉幋a和解碼的編碼表(GBK和UTF-8)都包含對(duì)這個(gè)字的對(duì)應(yīng)字節(jié)數(shù)組值,那么如果再用以下的方式重新編碼和解碼
        // 也還是亂碼,因?yàn)橐陨蟽蓚€(gè)編碼表(GBK和UTF-8)都包含對(duì)這個(gè)字的對(duì)應(yīng)數(shù)值,當(dāng)?shù)诙卧诰幋a解碼,而又他們的對(duì)應(yīng)數(shù)值又不
        // 一樣,所以解碼出來還是亂碼。所示例子ISO8859-1不包含對(duì)漢字的編碼和解碼。
        byte[] b2 = s1.getBytes("ISO8859-1");
        System.out.println(Arrays.toString(b2));
        String s2 = new String(b2, "GBK");
        System.out.println("s2 = " + s2);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 國(guó)家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報(bào)批稿:20170802 前言: 排版 ...
    庭說閱讀 11,184評(píng)論 6 13
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評(píng)論 18 399
  • 一、溫故而知新 1. 內(nèi)存不夠怎么辦 內(nèi)存簡(jiǎn)單分配策略的問題地址空間不隔離內(nèi)存使用效率低程序運(yùn)行的地址不確定 關(guān)于...
    SeanCST閱讀 7,883評(píng)論 0 27
  • 1 小趙不是個(gè)鼓號(hào)手,但是他們小學(xué)的鼓號(hào)隊(duì)隊(duì)員,可他從來沒有吹響過他的小號(hào)。而負(fù)責(zé)鼓號(hào)隊(duì)訓(xùn)練的大隊(duì)輔導(dǎo)員完全沒有開...
    了睞閱讀 206評(píng)論 0 0
  • 無論什么 總有它的歸屬 都是猿猴后代 卻也分國(guó)籍膚色 都是社會(huì)一員 依然有三六九等 不是同個(gè)量級(jí) 根本不能匹配 就...
    叫我梅芳就好閱讀 227評(píng)論 0 1