Java IO字节流

注意

(1)使用字节流写入String时,不用writerUTF()方法(在写出用于Java虚拟机的字符串时才使用)。而是使用writerChars()方法。所以需要内String限定一个长度。
(2)字节流以字节byte为最小单位。
char两个字节
String s = “abc”;
s.length ⇒ 3
但是s占6个字节

代码示例

package bytes.stream.employee;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Employee {
    /**
     * 名字的长度确定为20个字符,也就是40字节
     */
    static public final int EMPLOYEE_NAME_LENGTH = 20;
    static public final int EMPLOYEE_NAME_SIZE = EMPLOYEE_NAME_LENGTH * 2;
    static public final int EMPLOYEE_TOTAL_SIZE = EMPLOYEE_NAME_SIZE + 8 + 4 + 4 + 4;

    private String name;
    private double salary;
    private Calendar hireDay;


    public Employee(String name, double salary, Calendar hireDay) {
        super();
        this.name = name;
        this.salary = salary;
        this.hireDay = hireDay;
    }

    public Employee(String name, double salary, int year, int month, int dayOfMonth) {
        super();
        this.name = name;
        this.salary = salary;
        Calendar calendar = new GregorianCalendar(year, month, dayOfMonth);
        this.hireDay = calendar;
    }

    public Employee() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    public String toString() {
        return "Employee [name=" + name + ", salary=" + salary + ", hireDay=" + hireDay + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((hireDay == null) ? 0 : hireDay.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        long temp;
        temp = Double.doubleToLongBits(salary);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee other = (Employee) obj;
        if (hireDay == null) {
            if (other.hireDay != null)
                return false;
        } else if (!hireDay.equals(other.hireDay))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
            return false;
        return true;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public Calendar getHireDay() {
        return hireDay;
    }
    public void setHireDay(Calendar hireDay) {
        this.hireDay = hireDay;
    }


}
package bytes.stream.employee;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class EmployeePersistence {
    private String fileName = null;
    RandomAccessFile randomAccessFile = null;

    public EmployeePersistence(String fileName) throws FileNotFoundException {
        super();
        this.fileName = fileName;

        randomAccessFile = new RandomAccessFile(fileName, "rw");
    }

    public void add(Employee employee){
        try {
            randomAccessFile.seek(randomAccessFile.length());
            writeEmployee(employee);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void set(int index, Employee employee) throws IOException{
        checkOutOfRange(index);

        randomAccessFile.seek(index * Employee.EMPLOYEE_TOTAL_SIZE);
        writeEmployee(employee);
    }

    private void writeEmployee(Employee employee) throws IOException{
        writeFixedString(employee.getName(), Employee.EMPLOYEE_NAME_LENGTH);
        randomAccessFile.writeDouble(employee.getSalary());
        randomAccessFile.writeInt(employee.getHireDay().get(Calendar.YEAR));
        randomAccessFile.writeInt(employee.getHireDay().get(Calendar.MONTH));
        randomAccessFile.writeInt(employee.getHireDay().get(Calendar.DAY_OF_MONTH));
    }

    public Employee get(int index) throws IOException{
        checkOutOfRange(index);

        randomAccessFile.seek(index * Employee.EMPLOYEE_TOTAL_SIZE);
        String name = readFixedString(Employee.EMPLOYEE_NAME_LENGTH);
        double salary = randomAccessFile.readDouble();
        int year = randomAccessFile.readInt();
        int month = randomAccessFile.readInt();
        int dayOfMonth = randomAccessFile.readInt();

        return new Employee(name, salary, year, month, dayOfMonth);
    }

    private boolean checkOutOfRange(int index) throws IOException{
        if(((index * Employee.EMPLOYEE_TOTAL_SIZE) > randomAccessFile.length())
                || index < 0){
            throw new IndexOutOfBoundsException();
        }

        return false;
    }

    public void close(){
        if(randomAccessFile != null){
            try {
                randomAccessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void writeFixedString(String str, int fixedLength) throws IOException{
        for(int i = 0; i < fixedLength; i++){
            char c = 0;
            if(i < str.length()){
                c = str.charAt(i);
            }
            randomAccessFile.writeChar(c);
        }
    }

    private String readFixedString(int fixedLength) throws IOException{
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < fixedLength; i++){
            char c = randomAccessFile.readChar();
            if(c != 0){
                sb.append(c);
            }
        }

        return sb.toString();
    }


    public long employeesSize(){
        try {
            return randomAccessFile.length() / Employee.EMPLOYEE_TOTAL_SIZE;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public List<Employee> findAll() throws IOException{
        List<Employee> list = new ArrayList();
        for(int i = 0; i < employeesSize(); i++){
            list.add(get(i));
        }
        return list;
    }

    public void delete(int index) throws IOException{
        checkOutOfRange(index);

        byte[] buf = null;
        int readOff = 0;
        int len = 0;

        while(randomAccessFile.read(buf, readOff, len) != -1){

        }
    }

}
package bytes.stream.employee;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class EmployeePersistenceTest {
    EmployeePersistence employeePersistence = null;

    @Before
    public void before() throws FileNotFoundException {
        employeePersistence = new EmployeePersistence("F://bytes-employees.dat");
    }

    @After
    public void after(){
        employeePersistence.close();
    }

    @Test
    public void 建立文件(){
        try {
            Path path = Paths.get("F://bytes-employees.dat");
            Files.deleteIfExists(path);
            Files.createFile(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void 添加两个Employee() throws FileNotFoundException{

        Employee e1 = new Employee("wengchuqin", 21111.33, 1995, 07, 20);
        employeePersistence.add(e1);

        Employee e2 = new Employee("afang", 21111.33, 1995, 3, 3);
        employeePersistence.add(e2);

    }

    @Test
    public void get测试() throws IOException{
        System.out.println(employeePersistence.get(0));
        System.out.println(employeePersistence.get(1));
    }

    @Test
    public void set测试() throws IOException{
        Employee e = employeePersistence.get(0);
        System.out.println("before set : " + e);
        e.setName("啊哈哈哈哈");

        employeePersistence.set(0, e);
        e = employeePersistence.get(0);
        System.out.println("after set : " + e);
    }

    @Test
    public void findAll测试() throws IOException{
        System.out.println(employeePersistence.findAll());
    }

    @Test
    public void delete(int index){

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值