如何在java中使用數(shù)據(jù)流

本篇文章為大家展示了如何在java中使用數(shù)據(jù)流,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

創(chuàng)新互聯(lián)從2013年開始,先為萊蕪等服務(wù)建站,萊蕪等地企業(yè),進行企業(yè)商務(wù)咨詢服務(wù)。為萊蕪企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。

一、不帶緩沖的流

1.文件字節(jié)輸入流、文件字節(jié)輸出流

package anno;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test2 {
  public static void main(String[] args) {
    test1FileInputStream();
    test2FileInputStream();
    testFileOutputStream();
  }
  public static void test1FileInputStream() {
    String path = "F:\\test.txt";
    try {
      FileInputStream fs = new FileInputStream(path);
      //設(shè)置一個數(shù)組接收文件的內(nèi)容
      //需要注意的是,如果數(shù)組設(shè)置的太小,那么可能出現(xiàn)讀取的數(shù)據(jù)不完整或者亂碼等情況
      byte[] b = new byte[30];
      //文件輸入流對象有一個返回值,返回的是讀取數(shù)據(jù)的長度,如果讀取到一個數(shù)據(jù)了,還會向后讀一個,
      //當讀取完畢時會返回-1
      int len = 0;
      while((len=fs.read(b))!=-1) {
        //參數(shù)1是緩沖數(shù)據(jù)數(shù)組,參數(shù)2是從哪個位置開始轉(zhuǎn)換成字符串,參數(shù)3是總共轉(zhuǎn)換的長度
        System.out.println(new String(b, 0, len));
      }
      fs.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void test2FileInputStream() {
    String path = "F:\\test.txt";
    File f = new File(path);
    int l = (int) f.length();
    try {
      FileInputStream fs = new FileInputStream(path);
      byte[] b = new byte[l];
      //將讀取的數(shù)據(jù)存入到b中
      fs.read(b);
      //將b轉(zhuǎn)換成字符串并輸出
      System.out.println(new String(b));
      fs.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void testFileOutputStream() {    //如果不存在該文件,則系統(tǒng)會新建一個
    String path2 = "F:\\test2.txt";
    try {
      FileOutputStream fo = new FileOutputStream(path2);
      String str = "這是我測試的輸入";
      fo.write(str.getBytes());//將數(shù)據(jù)寫到byte中
      fo.flush();//將內(nèi)存中的數(shù)據(jù)寫到文件中
      fo.close();//關(guān)閉
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

在運行的過程中會遇到一些問題,比如說設(shè)置的byte數(shù)組來接收讀取的數(shù)據(jù),如果初始化長度給的比較小,那么讀取的數(shù)據(jù)就不全,在進行test1FileInputStream()的實驗中,即使按照:

  int len = 0;
      while((len=fs.read(b))!=-1) {
        //參數(shù)1是緩沖數(shù)據(jù)數(shù)組,參數(shù)2是從哪個位置開始轉(zhuǎn)換成字符串,參數(shù)3是總共轉(zhuǎn)換的長度
        System.out.println(new String(b, 0, len));
      }

進行輸出,如果byte設(shè)置的還是太小,就會出現(xiàn):

這是我新建的test.txt?
??件

這種亂碼問題,于是進行了第二種方法的嘗試,即在傳入數(shù)據(jù)之前首先獲得要接收多少字節(jié)的數(shù)據(jù),然后在進行接收(借鑒之前在golang中文件讀取并顯示的思想),然后就沒有問題了,即test2FileInputStream()。

輸出結(jié)果:

這是我新建的test.txt文件

2.使用字節(jié)流將一個文件復制到指定的文件夾下

public static void copyFile() {
    String path = "F:\\test.txt";
    String path3 = "F:\\test2.txt";
    try {
      FileInputStream fi = new FileInputStream(path);
      FileOutputStream fo = new FileOutputStream(path3);
      File f = new File(path);
      int l = (int) f.length();
      byte[] b = new byte[l];
      int len = 0;
      while((len=fi.read(b))!=-1) {
        fo.write(b,0,len);
      }
      fo.flush();
      fo.close();
      fi.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

綜合使用之前讀取的方式。

3.文件字符輸入流、文件字符輸出流

public static void testFileReader() {
    String path = "F:\\test.txt";
    try {
      FileReader fr = new FileReader(path);
      //注意這里是char類型的數(shù)組了
      char[] c = new char[20];
      int len = 0;
      while((len=fr.read(c))!=-1) {
        System.out.println(new String(c, 0, len));
      }
      fr.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void testFileWriter() {
    String path2 = "F:\\test2.txt";
    try {
      FileWriter fw = new FileWriter(path2);
      String str = "這是我測試的輸入";
      //注意這里可以直接寫入字符串
      fw.write(str);
      fw.flush();//將內(nèi)存中的數(shù)據(jù)寫到文件中
      fw.close();//關(guān)閉
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

需要注意的是定義char數(shù)組時仍然是需要知道數(shù)據(jù)是有多少字符的,不然長度不夠,顯示不全或者寫入不全。(這里暫時還未了解怎么處理)

4.使用字符流將一個文件復制到指定的文件夾下

public static void copyFile2() {
    String path = "F:\\test.txt";
    String path3 = "F:\\test2.txt";
    try {
      FileReader fr = new FileReader(path);
      FileWriter fw = new FileWriter(path3);
      char[] c = new char[30];
      int len = 0;
      while((len=fr.read(c))!=-1) {
        fw.write(c,0,len);
      }
      fw.flush();
      fw.close();
      fr.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }

二、帶緩沖的流

為了提高數(shù)據(jù)的讀寫速度,java API提供了帶緩沖功能的流類,在使用這些流類時,會創(chuàng)建一個內(nèi)部緩沖區(qū)數(shù)組。

根據(jù)數(shù)據(jù)操作單位可以把緩沖流分為:BufferedInputStream/BufferedOutputStream和BufferedReader/BufferedWriter。

緩沖流要“套接”在相應(yīng)的節(jié)點流之上,對讀寫的數(shù)據(jù)提供了緩沖的功能,提高了讀寫的效率,同時增加了些新方法。對于輸出的緩沖流,寫出的數(shù)據(jù)都會先在內(nèi)存中緩存,使用flush()會將在內(nèi)存中的數(shù)據(jù)立即寫出。

1.緩沖字節(jié)輸入流、緩沖字節(jié)輸出流

package anno;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test4 {
  public static void main(String[] args) throws IOException {
    testBufferedInputStream();
    testBufferedOutputStream();
    copyFile();
  }
  public static void testBufferedInputStream() throws IOException {
    FileInputStream fi = new FileInputStream("F:\\test.txt");
    //把文件字節(jié)輸入流放入到緩沖輸入流中
    BufferedInputStream bi = new BufferedInputStream(fi);
    byte[] b = new byte[35];
    int len = 0;
    while((len=bi.read(b))!=-1) {
      System.out.println(new String(b, 0, len));
    }
    bi.close();
    fi.close();
  }
  public static void testBufferedOutputStream() throws IOException {
    FileOutputStream fo = new FileOutputStream("F:\\test3.txt");
    //把文件字節(jié)輸入流放入到緩沖輸入流中
    BufferedOutputStream bo = new BufferedOutputStream(fo);
    String str = "這是我測試的內(nèi)容";
    bo.write(str.getBytes());
    bo.flush();
    bo.close();
    fo.close();
  }
  
  public static void copyFile() {
    String path = "F:\\test.txt";
    String path3 = "F:\\test2.txt";
    try {
      FileInputStream fi = new FileInputStream(path);
      BufferedInputStream bi = new BufferedInputStream(fi);
      FileOutputStream fo = new FileOutputStream(path3);
      BufferedOutputStream bo = new BufferedOutputStream(fo);
      File f = new File(path);
      int l = (int) f.length();
      byte[] b = new byte[l];
      int len = 0;
      while((len=bi.read(b))!=-1) {
        bo.write(b,0,len);
      }
      bo.flush();
      bo.close();
      fo.close();
      bi.close();
      fi.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }
}

2.緩沖字符輸入流、緩沖字符輸出流

package anno;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Test3 {
  
  public static void main(String[] args) {
    testBufferedReader();
    testBufferedWriter();
    copyFile();
  }
  
  public static void testBufferedReader() {
    String path = "F:\\test.txt";
    try {
      FileReader fr = new FileReader(path);
      BufferedReader br = new BufferedReader(fr);
      char[] c = new char[17];
      int len = 0;
      while((len=br.read(c))!=-1) {
        System.out.println(new String(c, 0, len));
      }
      br.close();
      fr.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void testBufferedWriter() {
    String path2 = "F:\\test2.txt";
    try {
      FileWriter fw = new FileWriter(path2);
      BufferedWriter bw = new BufferedWriter(fw);
      String str = "這是我測試的輸入";
      bw.write(str);//將數(shù)據(jù)寫到chars中
      bw.flush();//將內(nèi)存中的數(shù)據(jù)寫到文件中
      bw.close();
      fw.close();//關(guān)閉
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void copyFile() {
    String path = "F:\\test.txt";
    String path3 = "F:\\test2.txt";
    try {
      FileReader fr = new FileReader(path);
      BufferedReader br = new BufferedReader(fr);
      FileWriter fw = new FileWriter(path3);
      BufferedWriter bw = new BufferedWriter(fw);
      char[] c = new char[30];
      int len = 0;
      while((len=br.read(c))!=-1) {
        bw.write(c,0,len);
      }
      bw.flush();
      bw.close();
      fw.close();
      br.close();
      fr.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }

}

三、轉(zhuǎn)換流:用于字節(jié)流和字符流之間的轉(zhuǎn)換

java Api提供了兩個轉(zhuǎn)換流:InputStreamReader和OutputSreamWriter。

當字節(jié)流中的數(shù)據(jù)都是字符時,轉(zhuǎn)換成字符流操作更高效

package anno;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Test5 {
  public static void main(String[] args) throws IOException {
    testInputStreamReader();
    testOutputStreamWriter();
  }
  public static void testInputStreamReader() throws IOException {
    FileInputStream fi = new FileInputStream("F:\\test.txt");
    //字節(jié)流轉(zhuǎn)換成字符流
    //注意轉(zhuǎn)換成的編碼要和讀取的文件一致
    InputStreamReader ir = new InputStreamReader(fi,"utf-8");
    char[] c = new char[17];
    int len = 0;
    while((len=ir.read(c))!=-1) {
      System.out.println(new String(c, 0, len));
    }
    ir.close();
    fi.close();
  }
  public static void testOutputStreamWriter() throws IOException {
    FileOutputStream fo = new FileOutputStream("F:\\test3.txt");
    //轉(zhuǎn)換字節(jié)輸出流為字符輸出流
    OutputStreamWriter ow = new OutputStreamWriter(fo,"utf-8");
    String str = "這是我測試的內(nèi)容";
    ow.write(str);
    ow.flush();
    ow.close();
    fo.close();
  }
  
  public static void copyFile() {
    String path = "F:\\test.txt";
    String path3 = "F:\\test2.txt";
    try {
      FileInputStream fi = new FileInputStream(path);
      BufferedInputStream bi = new BufferedInputStream(fi);
      FileOutputStream fo = new FileOutputStream(path3);
      BufferedOutputStream bo = new BufferedOutputStream(fo);
      File f = new File(path);
      int l = (int) f.length();
      byte[] b = new byte[l];
      int len = 0;
      while((len=bi.read(b))!=-1) {
        bo.write(b,0,len);
      }
      bo.flush();
      bo.close();
      fo.close();
      bi.close();
      fi.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }
}

四、標準輸入輸出流

package anno;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test6 {
  public static void main(String[] args) throws IOException {
//    testSystemIn();
    testWriterToTxt();
  }
  public static void testSystemIn() throws IOException {
    //創(chuàng)建一個獲取鍵盤輸入的輸入流
    InputStreamReader ir = new InputStreamReader(System.in);
    //將輸入流放在緩沖中
    BufferedReader br = new BufferedReader(ir);
    String str = "";
    while((str = br.readLine())!=null) {
      System.out.println(str);
    }
  }
  //將控制臺的輸入寫入到txt文件中
  public static void testWriterToTxt() throws IOException {
    //創(chuàng)建一個獲取鍵盤輸入的輸入流
    InputStreamReader ir = new InputStreamReader(System.in);
    //將輸入流放在緩沖中
    BufferedReader br = new BufferedReader(ir);
    BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\test5.txt"));
    String line = "";
    while((line = br.readLine())!=null) {
      if (line.equals("over")) {
        break;
      }
      bw.write(line);
    }
    bw.flush();
    bw.close();
    br.close();
    ir.close();
  }
}

五、數(shù)據(jù)流

package anno;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test7 {
  public static void main(String[] args) throws IOException {
    testDataOutputStream();
    testDataInputStream();
  }
  //用數(shù)據(jù)輸出流寫到文件中的基本類型數(shù)據(jù)是亂碼,不能辨認出來,需要數(shù)據(jù)輸入流讀取
  public static void testDataOutputStream() throws IOException {
    DataOutputStream ds = new DataOutputStream(new FileOutputStream("F:\\test6.txt"));
    ds.writeDouble(1.35d);
    ds.flush();
    ds.close();
  }
  public static void testDataInputStream() throws IOException {
    DataInputStream ds = new DataInputStream(new FileInputStream("F:\\test6.txt"));
    System.out.println(ds.readDouble());
    ds.close();
  }
}

六、對象流

用于存儲和讀取對象的處理流,它的強大之處就是可以把java中對象寫入到數(shù)據(jù)源中,也能把對象從數(shù)據(jù)源中還原出來。

序列化:用ObjectOutputStream類將一個對象下入io流中;

反序列化:用ObjectInputStream類從io流中恢復對Java對象;

package anno;

import java.io.Serializable;

public class Person implements Serializable{
  //用來標識的UID
  private static final long serialVersionUID = 1L;
  String name;
  int age;
}
package anno;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test8 {
  public static void main(String[] args) throws IOException, ClassNotFoundException {
//    testSerializable();
    testDeSerializable();
  }
  //序列化
  public static void testSerializable() throws IOException {
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:\\test7.txt"));
    Person p = new Person();
    p.name = "tom";
    p.age = 12;
    oos.writeObject(p);
    oos.flush();
    oos.close();
  }
  //反序列化
  public static void testDeSerializable() throws IOException, ClassNotFoundException {
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\test7.txt"));
    Person p = null;
    Object obj = null;
    obj = ois.readObject();
    p = (Person) obj;
    System.out.println(p.name);
    System.out.println(p.age);
    ois.close();
  }
}

七、RandomAccessFile

支持隨機訪問的方式,程序可以直接跳轉(zhuǎn)到文件的任意位置地方來進行讀寫。支持只訪問文件的部分內(nèi)容,可以向已存在的文件后追加內(nèi)容。

RandomAccessFile對象包含一個記錄指針,用以標記當前讀寫的位置。

RandomAccessFile類對象可以自由地移動和記錄指針:

  • long getFilePoint():獲取文件記錄指針的當前位置;

  • void seek(long pos):將文件記錄指針移動到指定位置;

package anno;

import java.io.IOException;
import java.io.RandomAccessFile;

public class Test9 {
  public static void main(String[] args) throws IOException {
//    testRandomAccessFileRead();
    testRandomAccessFileWrite();
  }
  public static void testRandomAccessFileRead() throws IOException {
    //構(gòu)造方法有兩個參數(shù),參數(shù)一為路徑,參數(shù)二為訪問方式
    //r:只讀
    //rw:可寫可讀
    //rwd:可寫可讀,同步內(nèi)容跟新
    //rws:可寫可讀,同步內(nèi)容和元數(shù)據(jù)跟新;
    RandomAccessFile acf = new RandomAccessFile("F:\\test7.txt","r");
    //設(shè)置文件起始的讀取位置
    acf.seek(5);
    byte[] b = new byte[35];
    int len = 0;
    while((len=acf.read(b))!=-1) {
      System.out.println(new String(b, 0, len));
    }
    acf.close();
  }
  public static void testRandomAccessFileWrite() throws IOException {
    //構(gòu)造方法有兩個參數(shù),參數(shù)一為路徑,參數(shù)二為訪問方式
    //r:只讀
    //rw:可寫可讀
    //rwd:可寫可讀,同步內(nèi)容跟新
    //rws:可寫可讀,同步內(nèi)容和元數(shù)據(jù)跟新;
    RandomAccessFile acf = new RandomAccessFile("F:\\test7.txt","rw");
    //設(shè)置文件起始的寫入位置,0代表開頭,acf.length代表文件末尾
    acf.seek(acf.length());
    acf.write("你好".getBytes());
    acf.close();
  }
}

上述內(nèi)容就是如何在java中使用數(shù)據(jù)流,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

本文名稱:如何在java中使用數(shù)據(jù)流
標題URL:http://muchs.cn/article48/ihgphp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、標簽優(yōu)化虛擬主機、網(wǎng)站建設(shè)、網(wǎng)站收錄網(wǎng)站排名

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)