Java Cơ Bản Bài 10: Tạo, Đọc Và Ghi File Trong Java
Trong bài này mình sẽ hướng dẫn cho các bạn cách cơ bản để tạo, ghi và đọc một file trong Java.
Tạo file, folder
Tạo file:Trong ví dụ trên chương trình sẽ tạo ra 1 file demo.txt trong ổ đĩa E.Filef=newFile("E:\\demo.txt");try{f.createNewFile();// cau lenh tao file}catch(IOException e) {// TODO Auto-generated catch blocke.printStackTrace(); }
Tạo Folder:
Trong ví dụ trên chương trình sẽ tạo ra thư mục demo trong ổ đĩa E.Filedir=newFile("E:\\demo");dir.mkdir();// cau lenh tao thu muc
Ghi File
try { Filef=newFile("E:\\demo.txt"); if (!f.exists()) {// Neu file chua ton tai thi tao 1 filef.createNewFile(); } FileWriterfw=newFileWriter(f);// tao mot doi tuong fw ghi cac luong ki tu vao fileBufferedWriterbw=newBufferedWriter(fw);// tao mot doi tuong truyen cac luong ky tu vao fwStringdata; System.out.println("Nhap du lieu muon ghi vao file"); Scannernhap=newScanner(System.in); data =nhap.nextLine(); bw.write(data);//truyen du lieu vao fwbw.close(); //dong truyen du lieu vao fw fw.close(); //dong viec ghi du lieu vao file } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
Đọc file
Filef=newFile("E:\\demo.txt");try{ FileReaderfr=newFileReader(f);// tao doi tuong doc fileBufferedReaderbr= new BufferedReader(fr);// tao doi tuong doc du lieu tu doi tuong frStringdata= ""; while((data=br.readLine())!=null){//doc du lieuSystem.out.println(data); } }catch(IOException e) {// TODO Auto-generated catch blocke.printStackTrace(); }

Post a Comment