1. First create a Mybook objects
public class MyBook { private String name; private String author; private LocalDate date; public MyBook(){ } public MyBook(String name,String author,int year,int month,int day){ this.name=name; this.author=author; this.date=LocalDate.of(year,month,day); } public String getName() { return name; } public String getAuthor() { return author; } public LocalDate getDate() { return date; } }
2. Write operation
public class MyFileTest { public static void main(String[] args) throws FileNotFoundException { //初始化数组 MyBook[] books=new MyBook[4]; books[0]=new MyBook("coreJava","Unknown",2012,2,6); books[1]=new MyBook("coreJava","Unknown",2012,2,6); books[2]=new MyBook("coreJava","Unknown",2012,2,6); books[3]=new MyBook("coreJava","Unknown",2012,2,6); //写操作 try(PrintWriter out=new PrintWriter(new FileOutputStream("book.txt"))){ writeData(out,books); } } private static void writeData(PrintWriter out, MyBook[] books) { Out.println (books.length); // outputs are several objects, the latter use to read for (MyBook the myBook: Books) { writeBook(out,myBook); } } private static void writeBook(PrintWriter out, MyBook myBook) { out.println(myBook.getName()+"|"+myBook.getAuthor()+"|"+myBook.getDate()); } }
Note:
1.PrintWriter objects: text print format strings and numbers, is a subclass of Writer
Common constructors: /PrintWriter(String fileName, String csn)
PrintWriter(OutputStream out),这里采用的第二种,FileOutputStream是OutputStream的子类
try 2. stream {} with: automatically performing close (after completion of program execution)
3.InputStream / OutputStream: reads / writes a sequence of bytes of input and output streams
Reader / Writer: read two-byte sequence based on the value of char
Usually read and write operations write their subclasses using a discharge method in the present embodiment, the use PrintWriter println () output
4.FileInputStream / FileOutputStream no specific method for read and write text, (read (), write () can only read a single byte), their role is to obtain flow.
Stream to construct the object having the corresponding functions.