上節(jié)我們講到「Java中常用流:緩沖流」,本節(jié)我們學(xué)習(xí)數(shù)據(jù)流和對象流~
?數(shù)據(jù)流數(shù)據(jù)流將“基本數(shù)據(jù)類型變量”作為數(shù)據(jù)源,從而允許程序以與機(jī)器無關(guān)方式從底層輸入輸出流中操作java基本數(shù)據(jù)類型。??
DataInputStream和DataOutputStream提供了可以存取與機(jī)器無關(guān)的所有Java基礎(chǔ)類型數(shù)據(jù)(如:int,double?等)的方法。
【示例1】DataInputStream和DataOutputStream的使用
package?com.bjsxt.io;
import?java.io.*;
public?class?TestDataStream {
????public?static?void?main(String[]?args) {
??????? DataOutputStream?dos?=?null;
??????? DataInputStream?dis?=?null;
??????? FileOutputStream?fos?=?null;
??????? FileInputStream??fis?=?null;
????????try?{
?????????????fos?=?new?FileOutputStream("D:/data.txt");
?????????????fis?=?new?FileInputStream("D:/data.txt");
?????????????dos?=?new?DataOutputStream(new?BufferedOutputStream(fos));
?????????????dis?=?new?DataInputStream(new?BufferedInputStream(fis));
?????????????//將如下數(shù)據(jù)寫入到文件中
?????????????dos.writeDouble(Math.random());
?????????????dos.writeBoolean(true);
?????????????dos.writeInt(10);
?????????????dos.writeChar('a');
?????????????dos.flush();?? ??//將流中數(shù)據(jù)寫入到文件中
?????????????//從文件中直接讀取基本數(shù)據(jù)
???????????? System.out.println("double: "?+?dis.readDouble());
???????????? System.out.println("boolean: "?+?dis.readBoolean());
???????????? System.out.println("int: "?+?dis.readInt());
???????????? System.out.println("char: "?+?dis.readChar());
??????? }?catch?(IOException?e) {
?????????????e.printStackTrace();
??????? }?finally?{
?????????????try?{
?????????????????if(dos!=null){
?????????????????????dos.close();
???????????????? }
???????????? }?catch?(IOException?e) {
?????????????????e.printStackTrace();
???????????? }
?????????????try?{
?????????????????if(dis!=null){
?????????????????????dis.close();
???????????????? }
???????????? }?catch?(IOException?e) {
?????????????????e.printStackTrace();
???????????? }
?????????????try?{
?????????????????if(fos!=null){
?????????????????????fos.close();
???????????????? }
???????????? }?catch?(IOException?e) {
?????????????????e.printStackTrace();
???????????? }
?????????????try?{
?????????????????if(fis!=null){
?????????????????????fis.close();
???????????????? }
???????????? }?catch?(IOException?e) {
?????????????????e.printStackTrace();
???????????? }
??????? }
??? }
}
對象流
ObjectInputStream/ObjectOutputStream是以“對象”為數(shù)據(jù)源。經(jīng)常使用對象流將對象數(shù)據(jù)進(jìn)行序列化和反序列化操作。注:后續(xù)文章會(huì)詳細(xì)講解<Java對象的序列化和反序列化>
「全棧Java筆記」是一部能幫大家從零到一成長為全棧Java工程師系列筆記。筆者江湖人稱 Mr. G,10年Java研發(fā)經(jīng)驗(yàn),曾在神州數(shù)碼、航天院某所研發(fā)中心從事軟件設(shè)計(jì)及研發(fā)工作,從小白逐漸做到工程師、高級工程師、架構(gòu)師。精通Java平臺(tái)軟件開發(fā),精通JAVAEE,熟悉各種流行開發(fā)框架。
? 筆記包含從淺入深的六大部分:
? A-Java入門階段
? B-數(shù)據(jù)庫從入門到精通
? C-手刃移動(dòng)前端和Web前端
? D-J2EE從了解到實(shí)戰(zhàn)
? E-Java高級框架精解
? F-Linux和Hadoop?