1.首先建立一個Mybook對象html
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.寫的操做java
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:api
1.PrintWriter對象:進行文本格式打印字符串和數字,是Writer的子類數組
經常使用的構造方法:PrintWriter(String fileName, String csn)
/PrintWriter(OutputStream out),這裏採用的第二種,FileOutputStream是OutputStream的子類
oracle
2.帶流的try{}:會在程序執行完成後自動執行close()this
3.InputStream/OutputStream:讀入/寫入一個字節序列的輸入輸出流spa
Reader/Writer:讀寫基於兩個字節序列的char值code
通常讀寫操做使用它們的子類的讀寫放法,本例中,使用PrintWriter中的println()進行輸出htm
4.FileInputStream/FileOutputStream 沒有具體的讀寫文本的方法,(read(),write()只能讀寫單字節),它們的做用就是來獲取流,用流來構造具備相應讀寫功能的對象。對象
3.讀操做
public class MyReaderFileTest { public static void main(String[] args) throws FileNotFoundException { //獲取文件流 FileInputStream fis=new FileInputStream("employee.txt"); //構建有讀文本功能的對象 try(Scanner in=new Scanner(fis,"utf-8")){ MyBook[] myBooks=readData(in); for (MyBook myBook:myBooks){ System.out.println(myBook); } } } private static MyBook[] readData(Scanner in) { int n=in.nextInt();//有4個數據 in.nextLine(); MyBook[] myBooks=new MyBook[n]; for (int i=0;i<n;i++){ myBooks[i]=readBook(in); } return myBooks; } private static MyBook readBook(Scanner in) { String line=in.nextLine(); String[] strs=line.split("\\|");//將以‘|’分開的部分組裝爲一個數組 String name=strs[0]; String author=strs[1]; LocalDate date=LocalDate.parse(strs[2]); int year=date.getYear(); int month=date.getMonthValue(); int day=date.getDayOfMonth(); return new MyBook(name,author,year,month,day); } }
成功讀取!代碼是CoreJava這本書上的,不得不說人家這代碼寫的真心溜!