Quick Get-JAVA-IO streams

The fourth stage IO

I 流

Preface:

Previous study we can only do something within the existing scope of certain closed, but this is obviously uninteresting, but also do not support us to achieve a number of complex needs, so Java IO streams to provide such a concept to facilitate our data operating

Use IO streams we can achieve some powerful features, such as copying files between mobile and other operations, or program files with external data storage or read, or to achieve a real-time chat program (network programming), which transmission of data is also used in our IO streams, we will design the content in the back, I started following IO streams of formal learning

Overview and Classification (a) IO streams

(1) concept

IO i.e., input / output (I / O), the concept of flow still has some strange

"Flow" literally flow appears similar concept is that directional flow, continuity, and may carry a number of things, and in our computer, "flow" is an ordered successive directional abstract description data. Its essence is the data transmission, according to their characteristics to various types of packaged as an abstract, a more convenient operation by the user

(2) Category

A: flow

  • Input streams - data is read
  • Output streams - data write

B: Data Type

  • Byte stream
    • Input stream of bytes --InputStream
    • Byte output stream --OutputStream
  • Jifuryu
    • Character-input stream --Reader
    • Character-output stream --Writer

note:

a: If we did not specify in what points, divided according to the default data type.

b: unless the file with notepad windows open we were able to read only the use of a stream of characters, it is recommended to use a byte stream.

(Ii) byte stream

(1) FileOutputStream write data

A: Procedure

  • Create an output byte stream object
  • Call writer () method
  • Release resources

B: Code reflects

FileOutputStream fos = new FileOutputStream("fos.txt");
for.write("hello".getBytes());
fos.close;

LF Action

Because different systems for different identification number is not the same line breaks

windows:\r\n linux:\n Mac:\r

And some of the common high-level notebook can identify any number of line breaks

How to achieve additional write data?

With the second parameter is a constructor to true to

FileOutputStream fos = new FileOutputStream("fos.txt", true);

(2) FileInputStream read data

A: Procedure

  • Create a byte input stream object
  • Call writer () method
  • Release resources

B: Code reflects

FileInputStream fis = new FileInputStream("fos.txt");
//使用FileInputStream对指定路径下内容进行读取,可以结合FileOutputStream实现对文件的操作
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("F:\\fos.txt");

        //方式一
        int by = 0;
        while ((by = fis.read()) != -1){
            System.out.print((char)by);
        }

        //方式二(这种方式更加快,推荐)
        //数组长度一般是1024或者1024的整数倍
        byte[] bys = new byte[1024];
        int len = 0;
        while((len = fis.read(bys))!=-1){
            System.out.print(new String(bys,0,len));
        }
        //释放资源
        fis.close();
    }
}

(3) byte stream buffer

//统计这段程序运行时间

long start = System.currentTimeMillis();
//受测试代码
long end = System.currentTimeMillis();
System.out.println("共耗时" + (end - start) + "毫秒");

Byte stream once read an array of speed obviously a lot faster than the speed of time to read and write a byte, which is added to the buffer effect of such an array, java itself in the design, but also take into account such a design (decoration design patterns explained later), thus providing a stream of byte buffer

//字节缓冲输出流
BuffereOutputStream
//字节缓冲输入流
BufferedInputStream
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedOutputStreamDemo {
    public static void main(String[] args) throws IOException {
//        FileOutputStream fos = new FileOutputStream("F:\\fos.txt");
//        BufferedOutputStream bos = new BufferedOutputStream(fos);
        
        //简单写法
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("F:\\fos.txt"));
        
        //写数据
        bos.write("hello".getBytes());
        //释放资源,注意不需要fos.close
        bos.close();
    }
}

Why not pass a specific file or file path, but passing a OutputStream object?

The reason is simple, only providing the byte buffer stream buffer for the efficient design. But then, really have to achieve read and write operations on the basic stream object.

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        long start = System.currentTimeMillis();

        method1("E:\\夜曲.mp3", "F:\\Test1.mp3");
        method2("E:\\夜曲.mp3", "F:\\Test2.mp3");
        method3("E:\\夜曲.mp3", "F:\\Test3.mp3");
        method4("E:\\夜曲.mp3", "F:\\Test4.mp3");
        long end = System.currentTimeMillis();
        System.out.println("共耗时" + (end - start) + "毫秒");
    }

    //基本字节流一次读写一个字符
    public static void method1(String srcString, String deskString) throws IOException {
        FileInputStream fis = new FileInputStream(srcString);
        FileOutputStream fos = new FileOutputStream(deskString);
        int by = 0;
        while ((by = fis.read()) != -1) {
            fos.write(by);
        }
        fis.close();
        fos.close();
    }

    //基本字节流一次读写一个字节数组
    public static void method2(String srcString, String deskString) throws IOException {
        FileInputStream fis = new FileInputStream(srcString);
        FileOutputStream fos = new FileOutputStream(deskString);
        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = fis.read(bys)) != -1) {
            fos.write(bys, 0, len);
        }
        fis.close();
        fos.close();
    }

    //高效字节流一次读写一个字节
    public static void method3(String srcString, String deskString) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcString));
        BufferedOutputStream bos = new 
            BufferedOutputStream(new FileOutputStream(deskString));
        int by = 0;
        while ((by = bis.read()) != -1) {
            bos.write(by);
        }
        bis.close();
        bos.close();
    }

    //高效字节流一次读写一个字节数组
    public static void method4(String srcString, String deskString) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcString));
        BufferedOutputStream bos = new 
            BufferedOutputStream(new FileOutputStream(deskString));
        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = bis.read(bys)) != -1) {
            bos.write(bys, 0, len);
        }
    }
}


//运行结果
共耗时125961毫秒
共耗时143毫秒
共耗时1356毫秒
共耗时29毫秒

This shows that the above four ways, the most efficient or final - high byte stream read a byte array once!

(3) Jifuryu

We in development, if you want to we can identify text for transmission of data, if we continue to use a byte stream we learned above, we find that the content is displayed garbled because the encoding appears the problem, but this time we will use our character stream, we could start with a simple understanding of the character stream encoding = byte stream +

(1) codec

Byte stream we already have a certain understanding, then what is the encoding and decoding it?

Coding information format or converted from one form to another form of the process; decoding is the inverse process of the encoding.

Let's use an example to look at its processes

//通过指定的字符集解码字节数组
String(byte[] bytes, String charsetName)
//使用指定的字符集合把字符串编码为字节数组
byte[] getBytes(String charsetName)
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class EncodingDemo {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "理想";

        //String - byte[] - 编码
        byte[] bys = s.getBytes();  //[-25, -112, -122, -26, -125, -77]
//        byte[] bys = s.getBytes("UTF-8");   //[-25, -112, -122, -26, -125, -77]
//        byte[] bys = s.getBytes("GBK"); //[-64, -19, -49, -21]
        System.out.println(Arrays.toString(bys));
        
        //byte[] - String - 解码
        String string = new String(bys);  //理想
//        String string = new String(bys,"UTF-8");    //理想
//        String string = new String(bys,"GBK");    //鐞嗘兂
        System.out.println(string);
    }
}

Send process: "ideal" - Numbers - Binary - Send

Reception: reception - Binary - Decimal - value - character - "ideal"

In fact, the simple conclusion is that:

Code: to become able to understand not read

Decoding: The read into can understand

(2) character input and output streams

OutputStreamWriter character output stream (written)

public OutputStreamWriter(OutputStream out)
public OutputStreamWriter(OutputStream out,String charsetName)

InputStreamReader character input stream (read)

public InputStreamReader(InputStream in)
public InputStreamReader(InputStream in,String charsetName)

OutputStreamWriter data write method

//写一个字符
public void write(int c)

//写一个字符数组
public void write(char[] cbuf)

//写一个字符数组的一部分
public void write(char[] cbuf,int off,int len)

//写一个字符串
public void write(String str)

//写一个字符串的一部分
public void write(String str,int off,int len)

OutputStreamWriter read data method

//读一个字符
public int read()

//第一个字符数组
public int read(char[] cbuf)

Character stream operational issues should be noted

flush () and close () the difference?

use Close : After closing the stream object, but to refresh buffers, closes stream object will not be able to continue to use the

flush : only flush the buffer after the refresh, the stream object can continue to use

Simple wording (2) the character stream

Naming flow is relatively long, and our common operations are implemented according to local default encoding, so, in order to simplify our writing flow converter provides a corresponding subclass

//输出流
FileWriter
//输入流
FileReader
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("b.txt"))
//等价
FileWriter fw = new FileWriter("b.txt"); (写出)

InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"))
//等价 
FileReader fr = new FileReader("a.txt"); (读取)

(3) character buffer stream

 BufferedWriter: character buffer output stream

Writes text character output stream, buffering characters so as to provide a single character strings and arrays efficient writing .

You can specify the size of the buffer, or accept the default size. In most cases, the default value is large enough.

BufferedReader: character input stream buffer

Read from the character in the input text stream, buffering characters so as characters, lines and arrays efficient reading .

The buffer size can be specified or default size may be used. In most cases, the default value is large enough.

special function

BufferedWriter:

//根据系统来决定换行符
public void newLine()

BufferedReader:

//一次读取一行数据,包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
public String readLine()

(Iv) IO stream Case

Byte stream Case

Case I: Copy single-stage folder

import java.io.*;

/*
 * 需求:复制单级文件夹
 *
 * 数据源:f:\\demo
 * 目的地:f:\\test
 *
 * 分析:
 *         A:封装目录
 *         B:获取该目录下的所有文本的File数组
 *         C:遍历该File数组,得到每一个File对象
 *         D:把该File进行复制
 */


public class CopyFolderDemo {
    public static void main(String[] args) throws IOException {
        File srcFloder = new File("F:\\demo");
        File deskFloder = new File("F:\\test");

        if (!deskFloder.exists()) {
            deskFloder.mkdirs();
        }

        File[] fileArray = srcFloder.listFiles();
        for (File file : fileArray) {
            String name = file.getName();
            //拼凑出每一个文件的路径
            File newFile = new File(deskFloder, name);
            copyFloder(file, newFile);
        }
    }

    public static void copyFloder(File file, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream bos = 
            new BufferedOutputStream(new FileOutputStream(newFile));

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

        bis.close();
        bos.close();

    }
}

Case II: Copy the specified files in the specified directory, and modify extension

import java.io.*;

/*
 * 需求:复制指定目录下的指定文件,并修改后缀名。
 * 指定的文件是:.txt文件。
 * 指定的后缀名是:.bat
 * 指定的目录是:test
 *
 * 数据源:f:\\demo\\A.txt
 * 目的地:f:\test\\A.bat
 *
 * 分析:
 *         A:封装目录
 *         B:获取该目录下的java文件的File数组
 *         C:遍历该File数组,得到每一个File对象
 *         D:把该File进行复制
 *         E:在目的地目录下改名
 */
public class CopyFolderDemo2 {
    public static void main(String[] args) throws IOException {
        File srcFloder = new File("F:\\demo");
        File destFloder = new File("F:\\test");

        if (!destFloder.exists()) {
            destFloder.mkdirs();
        }

        File[] fileArray = srcFloder.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return new File(dir, name).isFile() && name.endsWith(".txt");
            }
        });


        for (File file : fileArray) {
            String name = file.getName();
            File newFile = new File(destFloder, name);
            copyFile(file, newFile);
        }

        File[] deskFileArray = destFloder.listFiles();
        for (File destFile : deskFileArray) {
            String name = destFile.getName();
            String newName = name.replace(".txt", ".bat");

            File newFile = new File(destFloder, newName);
            destFile.renameTo(newFile);
        }
    }

    public static void copyFile(File file, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream bos = 
            new BufferedOutputStream(new FileOutputStream(newFile));

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

    }
}

Case 3: Copy the multi-level folder

import java.io.*;

/*
 * 需求:复制多极文件夹
 *
 * 数据源:F:\\admin
 * 目的地:E:\\
 *
 * 分析:
 *         A:封装数据源File
 *         B:封装目的地File
 *         C:判断该File是文件夹还是文件
 *             a:是文件夹
 *                 就在目的地目录下创建该文件夹
 *                 获取该File对象下的所有文件或者文件夹File对象
 *                 遍历得到每一个File对象
 *                 回到C
 *             b:是文件
 *                 就复制(字节流)
 */
public class CopyFloderDemo3 {
    public static void main(String[] args) throws IOException {
        File srcFile = new File("F:\\admin");
        File destFile = new File("E:\\");
        copyFolder(srcFile, destFile);
    }


    private static void copyFolder(File srcFile, File destFile) throws IOException {
        if (srcFile.isDirectory()) {
            File newFolder = new File(destFile, srcFile.getName());
            newFolder.mkdirs();

            //获取该File对象下的所有文件或者文件夹File对象
            File[] fileArray = srcFile.listFiles();
            for (File file : fileArray) {
                //递归,继续判断
                copyFolder(file, newFolder);
            }

        } else {
            File newFile = new File(destFile, srcFile.getName());
            copyFile(srcFile, newFile);
        }
    }

    private static void copyFile(File srcFile, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        BufferedOutputStream bos = 
            new BufferedOutputStream(new FileOutputStream(newFile));

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

        bos.close();
        bis.close();
    }
}

Character stream Case

Case I: Random obtain the name of the case in a text file

import java.io.*;
import java.util.ArrayList;
import java.util.Random;

/*
 * 随机获取文本文件中的姓名案例
 *      需求:我有一个文本文件中存储了几个名称
 *      请大家写一个程序实现随机获取一个人的名字。
 *
 * 分析:
 *        A:把文本文件中的数据存储到集合中
 *        B:随机产生一个索引
 *        C:根据该索引获取一个值
 */
public class GetRandName {
    public static void main(String[] args) throws IOException {
        String path = "F:\\test.txt";
//        BufferedReader br = new BufferedReader(new FileReader(path));
        //默认记事本以ansi编码保存,但是使用FileReader默认使用UTF-8输出,所以使用上面语句会乱码
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "gb2312"));

        ArrayList<String> array = new ArrayList<>();
        String line = null;
        while ((line = br.readLine()) != null) {
            array.add(line);
        }
        br.close();

        Random r = new Random();
        int index = r.nextInt(array.size());

        String name = array.get(index);
        System.out.println("该幸运儿是:" + name);
    }
}

Case II: keyboard input student information in accordance with the sorting out and write a text file case

//Student类自行补充
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;

public class StudentDemo {
    public static void main(String[] args) throws IOException {
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s2.getSum() - s1.getSum();
                int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
                int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2;
                int num4 = num3 == 0 ? s1.getEnglish() - s2.getEnglish() : num3;
                int num5 = num4 == 0 ? s1.getName().compareTo(s2.getName()) : num4;
                return num5;
            }
        });

        for (int x = 1; x <= 3; x++) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入第" + x + "个学生成绩信息");
            System.out.println("姓名:");
            String name = sc.nextLine();
            System.out.println("语文成绩:");
            int chinese = sc.nextInt();
            System.out.println("数学成绩:");
            int math = sc.nextInt();
            System.out.println("英语成绩:");
            int english = sc.nextInt();

            Student s = new Student();
            s.setName(name);
            s.setChinese(chinese);
            s.setMath(math);
            s.setEnglish(english);
            ts.add(s);

            BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\students.txt"));
            bw.write("学生成绩信息如下");

            bw.newLine();
            bw.flush();
            bw.write("姓名-语文成绩-数学成绩-英语成绩");
            bw.newLine();
            bw.flush();
            for (Student stu : ts) {
                StringBuilder sb = new StringBuilder();
                sb.append(stu.getName() + "-" + stu.getChinese() + "-" + stu.getMath() + "-" + stu.getEnglish());
                bw.write(sb.toString());
                bw.newLine();
                bw.flush();
            }

            bw.close();
            System.out.println("学生成绩信息录入完毕");
        }
    }
}

Case 3: Log in Register Case (using IO)

Several collection of basic implemented on the front, the rest of the file the same, only need to rewrite files UserDaoImpl.java

Because of lengthy rest dao, pojo, test layer Please read before collection of several articles frame --List

package cn.bwh_05_LoginDemo.dao.impl;

import cn.bwh_05_LoginDemo.dao.UserDao;
import cn.bwh_05_LoginDemo.pojo.User;

import java.io.*;

/**
 * 这是用户操作的具体实现类 (IO)
 *
 * @author BWH_Steven
 * @version v1.1
 */
public class UserDaoImpl implements UserDao {
    private static File file = new File("User.txt");

    static {
        try {
            file.createNewFile();
        } catch (IOException e) {
            System.out.println("创建文件失败");
            e.printStackTrace();
        }
    }

    @Override
    public boolean isLogin(String username, String password) {
        boolean flag = false;
        BufferedReader br = null;
        String path = "user.txt";

        try {
            br = new BufferedReader(new FileReader(file));
            String line = null;
            while ((line = br.readLine()) != null) {
                //用户名--密码
                String[] datas = line.split("--");
                if (datas[0].equals(username) && datas[1].equals(password)) {
                    flag = true;
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("找不到登录所需要的信息文件");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("用户登录失败");
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    System.out.println("用户登录释放资源失败");
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    @Override
    public void regist(User user) {
        /*
         *  为注册的数据定义一个规则: 用户名--密码
         */
        BufferedWriter bw = null;
        String path = "user.txt";
        try {
            //为了保证数据是追加写入,所以必须加true
            bw = new BufferedWriter(new FileWriter(file, true));
            //bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path,true),"gb2312"));
            bw.write(user.getUsername() + "--" + user.getPassword());
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            System.out.println("用户注册失败");
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                System.out.println("用户注册释放资源失败");
                e.printStackTrace();
            }
        }
    }

}

end:

If there are any deficiencies, or content in the wrong place, welcome to give me a shout advice, crab everyone! ^ _ ^

If you can help, then it is to pay attention to me! (Updated series of articles will be the first time the public number)

Here we are strangers, all in the dream and work for their own ❤

Push a stick original Java technology public numbers: more than ten days over two

Guess you like

Origin www.cnblogs.com/ideal-20/p/11183404.html