案例来源:java基础案例教程,黑马程序员著
任务描述:
编写一个保存书店每日交易记录的程序,使用字节流将书店的交易信息记录在本地的csv文件中。文件命名格式为“销售记录”加上当天日期加上“.csv”后缀
实现:
(1)为方便保存图书的信息,可以将图书信息封装成一个实体类
public class Books {
private int id;
private String name; // 图书名称
private double price; // 图书单价
private int number; // 图书数量
private double money; // 总价
private String publish; // 出版社
/**************** 构造方法 ***************/
public Books() {
super();
}
public Books(int id, String name, double price, int number, double money,
String publish) {
super();
this.id = id;
this.name = name;
this.price = price;
this.number = number;
this.money = money;
this.publish = publish;
}
/*************** get/set ***************/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public String getPublish() {
return publish;
}
public void setPublish(String publish) {
this.publish = publish;
}
/************* 方法 **************/
/**
* 用于返回图书的详细信息
*/
@Override
public String toString() {
String message = "图书编号:" + id + " 图书名称:" + name + " 出版社: " + publish
+ " 单价" + price + " 库存数量:" + number;
return message;
}
}
(2)定义RecodeBooksOrder类来记录和操作图书信息
import java.util.ArrayList;
import java.util.Scanner;
public class RecodeBooksOrder {
// 创建一个集合用于模拟书架
static ArrayList<Books> booksList = new ArrayList<Books>();
public static void main(String[] args) {
// 初始化书架
init();
// 将书架上所有图书打印出来
for (int i = 0; i < booksList.size(); i++) {
System.out.println(booksList.get(i));
}
// 购买图书
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入图书编号:");
int bookId = sc.nextInt();
Books stockBooks = getBookById(bookId);
// 判断图书是否存在
if (stockBooks != null) {
System.out.println("当前图书信息:" + stockBooks);
System.out.println("请输入购买数量:");
int bookNumber = sc.nextInt();
// 判断库存
if (bookNumber <= stockBooks.getNumber()) {
// 将输入信息封装成Books对象
Books books = new Books(stockBooks.getId(), stockBooks
.getName(), stockBooks.getPrice(), bookNumber,
stockBooks.getPrice() * bookNumber, stockBooks
.getPublish());
// 保存本条数据
FileUtil.saveBooks(books);
// 修改库存
stockBooks.setNumber(stockBooks.getNumber() - bookNumber);
stockBooks.setMoney(stockBooks.getMoney()
- stockBooks.getPrice() * bookNumber);
} else {
System.out.println("库存不足");
}
} else {
System.out.println("图书编号输入错误");
}
}
}
/**
* 初始化书架
*/
private static void init() {
Books goods1 = new Books(101, "Java基础入门", 44.50, 100, 4450.00,
"清华大学出版社");
Books goods2 = new Books(102, "Java编程思想", 108.00, 50, 5400.00,
"机械工业出版社");
Books goods3 = new Books(103, "疯狂Java讲义", 99.00, 100, 9900.00,
"电子工业出版社");
booksList.add(goods1);
booksList.add(goods2);
booksList.add(goods3);
}
/**
* 根据图书编号查询图书信息
*/
private static Books getBookById(int bookId) {
for (int i = 0; i < booksList.size(); i++) {
Books thisBooks = booksList.get(i);
if (bookId == thisBooks.getId()) {
return thisBooks;
}
}
return null;
}
}
(3)定义工具类FileUtil保存图书信息
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileUtil {
public static final String SEPARATH_FIELD = ","; // 字段分隔 英文逗号
public static final String SEPARATH_LINE = "\r\n"; // 行分隔
/**
* 保存图书信息
**/
public static void saveBooks(Books books) {
/*
* 拼装文件
*/
Date date = new Date(); // 获取当前时间
DateFormat format = new SimpleDateFormat("yyyyMMdd"); // 定义日期格式
String name = "销售记录" + format.format(date) + ".csv"; // 拼接文件名
/*
* 写入文件
*/
FileInputStream in = null;
try {
in = new FileInputStream(name); // 判断本地是否存在此文件
if (in != null) {
in.close();
createFile(name, true, books); // 文件存在,采取修改文件的方式
}
} catch (FileNotFoundException e) {
createFile(name, false, books); // 文件不存在,新建文件
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 将图书的售出信息保存到本地,通过label标识是修改文件还是新建文件 name:文件名
* label:true表示存在,则修改当前文件;false表示不存在,则创建 books:图书信息
*/
public static void createFile(String name, boolean label, Books books) {
BufferedOutputStream out = null;
StringBuffer sbf = new StringBuffer(); // 用于拼接内容
try {
if (label) { // 当已存在当天的文件,则在文件内容后追加
out = new BufferedOutputStream(new FileOutputStream(name, true));
} else { // 不存在,则创建新文件
out = new BufferedOutputStream(new FileOutputStream(name));
String[] fileSort = new String[] { "图书编号", "图书名称", "购买数量",
"单价", "总价", "出版社" };
// 创建文件头部
for (String fileKey : fileSort) {
sbf.append(fileKey).append(SEPARATH_FIELD);
}
}
sbf.append(SEPARATH_LINE); // 追加换行符
// 添加图书的相关信息
sbf.append(books.getId()).append(SEPARATH_FIELD);
sbf.append(books.getName()).append(SEPARATH_FIELD);
sbf.append(books.getNumber()).append(SEPARATH_FIELD);
sbf.append(books.getPrice()).append(SEPARATH_FIELD);
sbf.append(books.getMoney()).append(SEPARATH_FIELD);
sbf.append(books.getPublish()).append(SEPARATH_FIELD);
// 写入
String str = sbf.toString();
byte[] b = str.getBytes();
for (int i = 0; i < b.length; i++) {
out.write(b[i]);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}