public class Book { private int no; // 编号 private String name; // 名称 private double price; // 单价 public Book(int no, String name, double price) { this.no = no; this.name = name; this.price = price; } public String toString() { return "图书编号:" + this.no + ",图书名称:" + this.name + ",图书单价:" + this.price + "\n"; } public static void write(List books) { FileWriter fw = null; try { fw = new FileWriter("E:\\myJava\\books.txt"); // 创建FileWriter对象 for (int i = 0; i < books.size(); i++) { fw.write(books.get(i).toString()); // 循环写入 } } catch (Exception e) { System.out.println(e.getMessage()); } finally { try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void read() { FileReader fr = null; BufferedReader br = null; try { fr = new FileReader("E:\\myJava\\books.txt"); br = new BufferedReader(fr); // 创建BufferedReader对象 String str = ""; while ((str = br.readLine()) != null) { // 循环读取每行数据 System.out.println(str); // 输出读取的内容 } } catch (Exception e) { System.out.println(e.getMessage()); } finally { try { br.close(); fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }如上述代码,分别使用字符文件输出流 FileWriter 和字符缓冲区输入流 BufferedReader 完成对图书信息的存储和读取功能。
public class Test14 { public static void main(String[] args) { Book book1 = new Book(1001, "C语言中文网Java教程", 159); Book book2 = new Book(1002, "C语言中文网C++教程", 259); List books = new ArrayList(); books.add(book1); books.add(book2); Book.write(books); System.out.println("********************图书信息******************"); Book.read(); } }3)运行程序,输出的图书信息,如下所示。打开 E:\myJava\books.txt 文件,该文件的内容如图 1 所示。
********************图书信息****************** 图书编号:1001,图书名称:C语言中文网Java教程,图书单价:159.0 图书编号:1002,图书名称:C语言中文网C++教程,图书单价:259.0
图1 文件保存的图书信息
本文链接:http://task.lmcjl.com/news/11034.html