Java IO 字符流例子

关于类的选取

输出流一般使用PrintWriter
输入流一般使用Scanner

注意事项

(1)行结束符。Windows系统是“\r\n”,UNIX系统是“\n”。
可以通过调用System.getProperty(”line.separator”)来获取。

代码示例:

package character.stream.employee;

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

public class Employee {
    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 character.stream.employee;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class EmployeeReader {
    private String fileName = null;

    public EmployeeReader(String fileName) {
        super();
        this.fileName = fileName;
    }

    public List<Employee> read() throws FileNotFoundException{
        Scanner scanner = new Scanner(new File(fileName));
        List<Employee> employees = new ArrayList<Employee>();

        while(scanner.hasNext()){
            String line = scanner.nextLine();
            String[] tokens = line.split("\\|");

            String name = tokens[0];
            double salary = Double.parseDouble(tokens[1]);
            int year = Integer.parseInt(tokens[2]);
            int month = Integer.parseInt(tokens[3]);
            int dayOfMonth = Integer.parseInt(tokens[4]);

            Employee employee = new Employee(name, salary, year, month, dayOfMonth);
            employees.add(employee);
        }

        scanner.close();
        return employees;
    }
}
package character.stream.employee;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Calendar;

public class EmployeeWriter {
    private String fileName = null;

    public EmployeeWriter(String fileName) {
        super();
        this.fileName = fileName;
    }

    public void write(Employee[] employees) throws FileNotFoundException{
        PrintWriter writer = new PrintWriter(new FileOutputStream(fileName));

        for(Employee employee : employees){
            StringBuffer sb = new StringBuffer();
            sb.append(employee.getName());
            sb.append("|");
            sb.append(employee.getSalary());
            sb.append("|");
            sb.append(employee.getHireDay().get(Calendar.YEAR));
            sb.append("|");
            sb.append(employee.getHireDay().get(Calendar.MONTH) + 1);
            sb.append("|");
            sb.append(employee.getHireDay().get(Calendar.DAY_OF_MONTH));

            writer.println(sb.toString());
        }

        writer.close();
    }
}
package character.stream.employee;

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

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


public class EmployeeTest {
    private String fileName = "F://test/employees.txt";
    EmployeeReader reader = null;
    EmployeeWriter writer = null;

    @Before
    public void before() throws FileNotFoundException {
        reader = new EmployeeReader(fileName);
        writer = new EmployeeWriter(fileName);
    }

    @Test
    public void 建立文件(){
        try {
            Path path = Paths.get("F://test/employees.txt");
            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);
        Employee e2 = new Employee("afang", 21111.33, 1995, 3, 3);

        writer.write(new Employee[]{e1, e2});
    }

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

    @Test
    public void test(){
        System.out.println(Charset.defaultCharset());
    }
}

结果:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值