讀取或儲存的資料為 String 或 基本資料型別 ( byte short char int long float double boolean)
※儲存成檔案
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 | import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataOutputStreamTest { public static void main(String[] args) { String filename="C:/Users/Administrator/Desktop/MyJava/student.data"; String name="TOM"; int eng=100; int math=95; float avg=(eng+math)/2.0f; try(DataOutputStream dos=new DataOutputStream(new FileOutputStream(filename))){ dos.writeUTF(name); //string dos.writeInt(eng); //int dos.writeInt(math); dos.writeFloat(avg); dos.close(); }catch(IOException e){ System.out.println(e); } } } |
※讀取檔案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class DataInputStreamTest { public static void main(String[] args) { String filename="C:/Users/Administrator/Desktop/MyJava/student.data"; try(DataInputStream dis=new DataInputStream(new FileInputStream(filename))){ String name=dis.readUTF(); int eng=dis.readInt(); int math=dis.readInt(); float avg=dis.readFloat(); dis.close(); System.out.println(name+" "+eng+" "+math+" "+avg); }catch(IOException e){ System.out.println(e); } } } |
沒有留言:
張貼留言