1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package Test; import java.io.*; public class Main{ public static void main(String[] args) { File f = new File("C:\\Users\\Duy\\Desktop\\liststudent.txt"); String ftxt = "Student ID, Student Name, Address, Phone \n"; if (f.canWrite()) { try { FileOutputStream fos = new FileOutputStream(f); DataOutputStream dos = new DataOutputStream(fos); for (Student st : arrayList) { String s = st.getStudentID() + "," + st.getStudentName() + "," + st.getAddress() + "," + st.getPhone() + " \n"; ftxt = ftxt + s; } dos.writeBytes(ftxt); dos.close(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } if (f.canRead()) { try { FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); String line = ""; while ((line = dis.readLine()) != null) { ftxt += line + "\n"; String[] strs = line.split("-"); Student s = new Student(strs[0], Integer.parseInt(strs[1]), Integer.parseInt(strs[2])); arr.add(s); } dis.close(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } } |