标签:inpu color day 字符 style 就是 data book 字符串
1.首先创建一个Mybook对象
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.写的操作
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);//输出有几个对象,后面的读要用到 for (MyBook myBook:books){ writeBook(out,myBook); } } private static void writeBook(PrintWriter out, MyBook myBook) { out.println(myBook.getName()+"|"+myBook.getAuthor()+"|"+myBook.getDate()); } }
Note:
1.PrintWriter对象:进行文本格式打印字符串和数字,是Writer的子类
常用的构造方法:PrintWriter(String fileName, String csn)
/PrintWriter(OutputStream out),这里采用的第二种,FileOutputStream是OutputStream的子类
2.带流的try{}:会在程序执行完成后自动执行close()
3.InputStream/OutputStream:读入/写入一个字节序列的输入输出流
Reader/Writer:读写基于两个字节序列的char值
一般读写操作使用它们的子类的读写放法,本例中,使用PrintWriter中的println()进行输出
4.FileInputStream/FileOutputStream 没有具体的读写文本的方法,(read(),write()只能读写单字节),它们的作用就是来获取流。
用流来构造具有相应功能的对象。
标签:inpu color day 字符 style 就是 data book 字符串
原文地址:https://www.cnblogs.com/liu-chen/p/11948944.html