70 likes | 191 Views
การโปรแกรมเชิงวัตถุด้วยภาษา JAVA. Text File Processing. มหาวิทยาลัยเนชั่น http:// www. nation. ac.th. บุรินทร์ รุจจนพันธุ์ . ปรับปรุง 7 มิถุนายน 255 6. เขียน String ออกเป็นแฟ้มอย่างง่าย. import java.io.*; class x { public static void main (String args[]) throws IOException {
E N D
การโปรแกรมเชิงวัตถุด้วยภาษา JAVA Text File Processing มหาวิทยาลัยเนชั่น http://www.nation.ac.th บุรินทร์ รุจจนพันธุ์ . ปรับปรุง 7 มิถุนายน 2556
เขียน String ออกเป็นแฟ้มอย่างง่าย import java.io.*; class x { public static void main (String args[]) throws IOException { byte[] s = "hello".getBytes(); FileOutputStream fout = new FileOutputStream("y.txt"); fout.write(s); fout.write(13); fout.write(10); fout.write(s); fout.close(); // 12 bytes } } http://www.thaiall.com/class/j06.htm
เขียนข้อมูลหลายบรรทัดในแฟ้มใหม่เขียนข้อมูลหลายบรรทัดในแฟ้มใหม่ import java.io.*; class x { public static void main(String args[])throws IOException{ FileOutputStream fout = new FileOutputStream("y.txt"); for(int i=65;i<65+26;i++) { fout.write(i); fout.write(13); fout.write(10); } fout.close(); } }
อ่านแฟ้มข้อมูลลงอาร์เรย์แบบ char import java.io.*; class x { public static void main(String args[])throws IOException{ int i = 0, n = 0; char b[] = new char[1]; FileReader fin = new FileReader("x.java"); while ((n = fin.read(b)) != -1) { System.out.println(i+" : "+b[0]); i = i + 1; } fin.close(); } }
อ่านข้อมูลจาก text file มาแสดง import java.io.*; class x { public static void main (String args[]) throws IOException { String b; FileReader fin = new FileReader("x.java"); BufferedReader bin = new BufferedReader (fin); while ((b = bin.readLine()) != null) { System.out.println(b); } fin.close(); } }
ไม่ใช้ throws ระดับ method class x { public static void main (String args[]) { String b; try{ java.io.FileReader fin = new java.io.FileReader("x.java"); java.io.BufferedReader bin = new java.io.BufferedReader (fin); while ((b = bin.readLine()) != null) { System.out.println(b); } fin.close(); } catch(Exception e) { } } }
การอ่านระเบียนข้อมูลแล้วแยกด้วย , import java.io.*; class x { public static void main(String args[])throws IOException{ int tot = 0; String b; String[] fields; FileReader fin = new FileReader("data.txt"); BufferedReader bin = new BufferedReader (fin); while ((b = bin.readLine()) != null) { fields = b.split(","); System.out.println(fields[0]); System.out.println("Name : " + fields[1]); System.out.println("Salary : " + fields[2]); tot = tot + Integer.parseInt(fields[2]); } System.out.println("Total : " + tot); fin.close(); }} http://www.thaiall.com/class/j07.htm