Java 09 experiments (IO stream) - test report

0. byte stream and binary files

My code

package javalearning;

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


class Student {
    private int id;
    private String name;
    private int age;
    private double grade;
    
    public Student(){
        
    }
    public Student(int id, String name, int age, double grade) {
        this.id = id;
        this.setName(name);
        this.setAge(age);
        this.setGrade(grade);
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        if (name.length()>10){
            throw new IllegalArgumentException("name's length should <=10 "+name.length());
        }
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        if (age<=0){
            throw new IllegalArgumentException("age should >0 "+age);
        }
        this.age = age;
    }
    public double getGrade() {
        return grade;
    }
    public void setGrade(double grade) {
        if (grade<0 || grade >100){
            throw new IllegalArgumentException("grade should be in [0,100] "+grade);
        }
        this.grade = grade;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + ", grade=" + grade + "]";
    }
    
}
public class Main {
    public static void main(String[] args)
    {
        
        String fileName="d:\\testStream\\0\\student.data";
        try(DataOutputStream dos=new DataOutputStream(new FileOutputStream(fileName)))
        {
            Student stu1=new Student(1,"zhang",13,80);
            dos.writeInt(stu1.getId());
            dos.writeUTF(stu1.getName());
            dos.writeInt(stu1.getAge());
            dos.writeDouble(stu1.getGrade());
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try(DataInputStream dis=new DataInputStream(new FileInputStream(fileName)))
        {
            int id=dis.readInt();
            String name=dis.readUTF();
            int age=dis.readInt();
            double grade=dis.readDouble();
            Student stu=new Student(id,name,age,grade);
            System.out.println(stu);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

My summary

A, Student object using DataOutputStream and FileOutputStream to write binary files student.data

  1. The difference between binary and text files
  • Binary files may be stored int / double / char .. basic data types, text files can store the type char. Thus reading a text file or stored procedures often need to use casts (similar to the parseInt)

2.try ... catch ... finally Precautions

  • catch multiple exceptions to the attention of abnormal write the order, unusual in general, the larger the (parent) to put back more. The eclipse can be used directly prompts directly generate abnormal themselves, convenient and not go wrong.

3. Use try..with ... resouces close the resource

  • Is jdk8 new syntax, you can define the last to be closed resources directly in the try (........) brackets, will automatically shut down after the end of the run, you do not need to shut down the traditional resources in the finally. See above usage code block.

1. stream of characters and text files

My code

Task 1

String fileName="d:\\testStream\\1\\Students.txt";
List<Student> studentList = new ArrayList<>();
        try(
            FileInputStream fis=new FileInputStream(fileName);
            InputStreamReader isr=new InputStreamReader(fis, "UTF-8");
            BufferedReader br=new BufferedReader(isr))
        {
            String line=null;
            while((line=br.readLine())!=null)
            {
                String[] msg=line.split("\\s+");
                int id=Integer.parseInt(msg[0]);
                String name=msg[1];
                int age=Integer.parseInt(msg[2]);
                double grade=Double.parseDouble(msg[3]);
                Student stu=new Student(id,name,age,grade);
                studentList.add(stu);
            }
        } 
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(studentList);

Task 2

public static List<Student> readStudents(String fileName)
    {
        List<Student> studentList = new ArrayList<>();
        try(
            FileInputStream fis=new FileInputStream(fileName);
            InputStreamReader isr=new InputStreamReader(fis, "UTF-8");
            BufferedReader br=new BufferedReader(isr))
        {
            String line=null;
            while((line=br.readLine())!=null)
            {
                String[] msg=line.split("\\s+");
                int id=Integer.parseInt(msg[0]);
                String name=msg[1];
                int age=Integer.parseInt(msg[2]);
                double grade=Double.parseDouble(msg[3]);
                Student stu=new Student(id,name,age,grade);
                studentList.add(stu);
            }
        } 
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return studentList;
    }

Task 3

String fileName="d:\\testStream\\1\\Students.txt";
try(
            FileOutputStream fos=new FileOutputStream(fileName,true);
            OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8");
            PrintWriter pw=new PrintWriter(osw))
        {
            pw.println();
            pw.print("4 一一 13 80");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Task 4

String fileName1="d:\\testStream\\1\\Students.dat";
try(
            FileOutputStream fos=new FileOutputStream(fileName1);
            ObjectOutputStream oos=new ObjectOutputStream(fos))
        {
            Student ts=new Student(5,"asd",14,60);
            oos.writeObject(ts);
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try(
            FileInputStream fis=new FileInputStream(fileName1);
            ObjectInputStream ois=new ObjectInputStream(fis))
        {
            Student newStudent =(Student)ois.readObject();
            System.out.println(newStudent);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

My summary

  • In task 2, 3, the program generates txt file is specified UTF-8 encoding. If subsequent artificially opened through the system comes Students.txt and save text document, the text becomes UTF-8-BOM encoded. So the error will run the program again, because the specified file is actually UTF-8 with the UTF-8-BOM is not the same, this problem has troubled me for some time now my solution is two-fold: no man save or use notepad ++ when people need to save.
  • Task 3 start PrintWriter directly overwrite the original file, through access to information, when constructing a FileOutputStream a true multi-pass it.
  • Task 4, the start is to make a stream of objects written in txt, the garbage will happen later found. Through access to information to know writeObject () role is to make an example in the form of files stored on the disk, and this file is written in binary form, so let the object stream processing file format is the bat, on the right.

2. buffered stream

My code

package javalearning;

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

public class Main2 {

    public static void main(String[] args) {
        String fileName="d:\\testStream\\2\\test.txt";
        try (PrintWriter pw = new PrintWriter(fileName);)
        {
            Random random=new Random();
            random.setSeed(100);
            double sum=0,aver;
            for (int i = 0; i < 1000_0000; i++) {
                int r=random.nextInt(10);
                sum+=r;
                pw.println(r);
            }
            aver=sum/1000_0000;
            System.out.format("%.5f", aver);
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

JUNIT test section

package javalearning;

import static org.junit.jupiter.api.Assertions.*;

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

import org.junit.jupiter.api.Test;

class testBufferedReader {
    String fileName="d:\\testStream\\2\\test.txt";
    @Test
    void testScanner() {
        try (   FileInputStream fis = new FileInputStream(fileName);
                Scanner sc=new Scanner(fis))
        {
            while(sc.hasNextInt())
            {
                sc.nextInt();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }finally
        {
            System.out.println("sc end");
        }
    }
    @Test
    void testBufferedReader() {
        try (   FileReader fr = new FileReader(fileName);
                BufferedReader br=new BufferedReader(fr))
        {
            String line=null;
            while((line=br.readLine())!=null)
            {
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }finally
        {
            System.out.println("br end");
        }
        
    }

}

My summary

  • Generating random numbers usually use less, each had to first find information when needed, and try to remember common usage.
  • When the random number written to the file, if using a print instead of println, text size will be the third of the println (1000_0000 3000_0000 bytes and bytes), the reason being not understand, did not write a carriage return, then ran out the results junit Scanner and BufferedReader time is about the same, and wrote Enter the time gap is very big.
  • JUNIT former method to be tested to add @Test

Guess you like

Origin www.cnblogs.com/damao33/p/11924697.html