- 使用字節流
- 讀取控制檯輸入
- 因爲System.in是InputStream的一個實例,然而InputStream只定義了一個讀取字節的輸入方法read()
- int read() throws IOException int read(byte data[]) throws IOException int read(byte data[],int start,int max) throws IOException
- import java.io.*;
- class javadir{
- public static void main(String args[]) throws IOException {
- byte data[]=new byte[111];
- System.out.println("Enter some characters:");
- System.in.read(data);
- System.out.print("you entered:");
- for(int i=0;i<10;i++) System.out.print((char)data[i]);
- }
- }
- 寫入控制檯輸出
- print,println是由類PrintStream定義的,PrintStream是一個從OutputStream派生出來的輸出流,所以它還執行低級別的方法write()
- 因此使用write()向控制檯寫實完全可行的
- import java.io.*;
- class javadir{
- public static void main(String args[]) {
- int b;
- b='D';
- System.out.write(b);
- System.out.write('\n');
- }
- }
- 使用字節流讀取文件
- Java可以讓你將一個字節組成的文件包含在一個基於字符的對象中,這在後面介紹
- 爲創建一個與文件相連接的字節流,需要使用FileInputStream,FileOutputStream,要打開文件,需要創建對象
- 從文件輸入
- 通過創建一個FileInputStream對象可以打開一個用於輸入的文件,下面是它最常用的構造函數
- FileInputStream(String filename) throws FileNotFoundException
- 需要使用read()方法從文件中讀取, 當處理完後應該用close()方法關閉它
- import java.io.*;
- class javadir{
- public static void main(String args[]) {
- int i;
- FileInputStream fin;
- if(args.length!=1){
- System.out.println("show file:");
- return;
- }
- try{
- fin=new FileInputStream(args[0]);
- }catch(FileNotFoundException exc){
- System.out.println("file not found");
- return; //需要加上
- }
- try{
- do{
- i=fin.read();
- if(i!=-1) System.out.print((char)i);
- }while(i!=-1);
- }catch(IOException exc){
- System.out.println("Error reading file");
- }
- try{
- fin.close();
- }catch(IOException exc){
- System.out.println("Error closing file");
- }
- }
- }
- 使用字節流寫入文件
- 爲打開一個文件用於輸出,需要創建一個FileOutputStream對象,下面是它的常用構造函數
- FileOutputStream(String filename) throws FileNotFoundException
- FileOutputStream(String filename,boolean append) throws FileNotFoundException
- 需要使用 void write(int byteval) throws IOException 來寫入文件
- 該方法向文件寫入byteval指定的字節,儘管byteval被聲明一個整數,但它只有低八位可以寫入文件
- 輸出的內容不會馬上寫到物理設備而會緩存
- 可以使用 void flush() throws IOException 不讓它緩存
- 輸出文件結束後,就必須使用close()關閉它
- 例子如下:
- import java.io.*;
- class javadir{
- public static void main(String args[]){
- FileInputStream fin;
- FileOutputStream finn;
- int i;
- if(args.length!=2){
- System.out.println("輸入的文件名不正確!");
- return;
- }
- try{
- fin=new FileInputStream(args[0]);
- finn=new FileOutputStream(args[1]);
- }catch(FileNotFoundException exc){
- System.out.println("文件不存在");
- return;
- }
- try{
- do{
- i=fin.read();
- if(i!=-1) finn.write(i);
- }while(i!=-1);
- }catch(IOException exc){
- System.out.println("讀取文件錯誤");
- }
- try{
- fin.close();
- finn.close();
- }catch(IOException exc){
- System.out.println("Error closing file");
- }
- }
- }
- 讀寫二進制數據
- 目前我們已經讀寫的字節包括ASCII字符,但是也可以讀取和寫入其他類型的數據,例如可以創建一個包含int double 的文件
- 要讀取和寫入Java的簡單類型的二進制值,需要使用DataInputStream和DataOutputStream
- DataOutputStream實現DataOutput接口,該接口定義了所有Java簡單類型向文件寫入的方法,有一點很重要的是:
- 數據寫入使用的是內部二進制數據而不是人們可讀的文本形式
- 以下是構造方法
- DataOutputStream(OutputStream os) 這裏的os是寫入數據的流,要向文件輸出,可以使用FileOutputStream爲該參數創建的對象
- void writeBoolean(boolean val)
- void writeByte(int val)
- void writeChar(int val)
- void writeDouble(double val)
- void writeInt(int val)
- void writeLong(long val)
- void writeShort(short val)
- void writeFloat(float val)
- DataInputStream實現DataInput接口,該接口定義了所有Java簡單類型讀取文件的方法
- DataInputStream是以二進制讀取數據的,而不是以可讀文本格式讀取數據
- 它的構造函數如下:
- DataInputStream(InputStream is) 這裏is是與創建DataInputStream的實例相關聯的流,要從文件讀取數據
- 可以使用FileInputStream爲該參數創建的對象
- boolean readBoolean() ......與上面相對應
- 例子如下:
- import java.io.*;
- class javadir{
- public static void main(String args[]){
- DataOutputStream dataout;
- DataInputStream datain;
- int i=10;
- double d=1209.33;
- boolean b=true;
- try{
- dataout=new DataOutputStream(new FileOutputStream("t.txt"));
- }catch(IOException exc){
- System.out.println("can not open the file");
- return;
- }
- try{
- System.out.println("Writing"+i);
- dataout.writeInt(i);
- System.out.println("Writing"+d);
- dataout.writeDouble(d);
- System.out.println("Writing"+b);
- dataout.writeBoolean(b);
- }catch(IOException exc){
- System.out.println("Write error");
- }
- try{
- dataout.close();
- }catch(IOException exc){
- System.out.println();
- return;
- }
- System.out.println();
- try{
- datain=new DataInputStream(new FileInputStream("t.txt"));
- }catch(IOException exc){
- System.out.println("can not open the file");
- return;
- }
- try{
- i=datain.readInt();
- System.out.println("Reading"+i);
- d=datain.readDouble();
- System.out.println("Reading"+d);
- b=datain.readBoolean();
- System.out.println("Reading"+b);
- }catch(IOException exc){
- System.out.println("can not read");
- }
- try{
- datain.close();
- }catch(IOException exc){
- System.out.println("Error closing file");
- }
- }
- }
- 隨即訪問文件
- RandomAccessFile類不是從InputStream 或 OutputStream 派生而來的,相反它實現定義I/O基本方法的接口DataInput 和DataOutput
- 構造函數如下:
- RandomAccessFile(String filename,String access) throws FileNotFoundException
- access確定了允許的文件訪問類型,如果是"r" 文件只能讀不能寫,如果是"rw"文件既可以讀也可以寫
- 這裏的 void seek(long newPos) throws IOException ,這裏的newPos 制定了新的文件位置發生位置
- RandomAccessFile實現了read()和write()方法,也可以使用如readInt(),writeDouble()...方法
- import java.io.*;
- class javadir{
- public static void main(String args[]){
- double data[]={12.3,34.4,26.7,26.7,98.4};
- double d;
- RandomAccessFile raf;
- try{
- raf=new RandomAccessFile("t.txt","rw");
- }catch(FileNotFoundException exc){
- System.out.println("File not Found");
- return;
- }
- try{
- for(int i=0;i<data.length;i++){
- raf.writeDouble(data[i]);
- }
- raf.seek(0);
- d=raf.readDouble();
- System.out.println("Value is"+d);
- raf.seek(2*8);
- d=raf.readDouble();
- System.out.println("Value is"+d);
- }catch(IOException exc){
- System.out.println("Seeking is Error");
- }
- try{
- raf.close();
- }catch(IOException exc){
- System.out.println("Error closing file");
- }
- }
- }
- 使用java字符流
- 使用字符流的控制檯輸入
- 因爲是一個System.in字節流,所以需要將System.in包含在某一類型的Reader中。讀取控制檯輸入最好的類是BufferedReader,
- 它支持緩衝輸入流。然而不能直接從System.in構造BufferedReader,必須首先將它轉換爲一個字符流,爲此,需要使用InputStreamReader把字節轉換爲字符
- 爲了獲得與System.in鏈接的InputStreamReader對象,需要使用下面的構造函數
- InputStreamReader(InputStream is) 因爲System.in引用一個InputStream對象,所以它用於InputStream對象
- 接下來使用一個BufferedStream 構造函數,如下:BufferedStream(Reader ir) 這裏ir是與創建的BufferedStream實例鏈接的流
- 下面的代碼創建了與鍵盤連接的流:BufferedStream br=new BufferedStream(new InputStreamReader(System.in)) br將成爲一個通過System.in與控制檯鏈接的字符流
- 使用read()方法讀取字符
- import java.io.*;
- class javadir{
- public static void main(String args[]) throws IOException {
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- char c;
- System.out.println("Enter some words");
- do{
- c=(char)br.read();
- System.out.println(c);
- }while(c!='.');
- }
- }
- 讀取字符串
- 爲從鍵盤讀取字符串,需要使用BufferedReader類的成員readLine();其基本形式如下:
- String readLine() throws IOException
- import java.io.*;
- class javadir{
- public static void main(String args[]) throws IOException {
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- String s;
- System.out.println("Enter Strings");
- do{
- s=br.readLine();
- System.out.println(s);
- }while(!s.equals("stop"));
- }
- }
- 使用字符流控制檯輸出
- 在java中向控制檯寫入的更好的方法是使用PrintStream流,它是一個字符流 其常用的一個構造函數如下:
- PrintStream(OutputStream os,boolean flushonNewline)
- PrintStream 支持包括Object在內的所有類型的print,println方法,如果變元不是簡單類型,PrintWrite將調用 toString() 方法
- 爲了使用PrintStream向控制檯寫入,需要爲輸出流指定System.out,在每一個println()調用之後刷新流, PrintStream pw=new PrintStream(System.out,true)
- import java.io.*;
- class javadir{
- public static void main(String args[]) throws IOException {
- PrintStream pw=new PrintStream(System.out,true);
- int i=10;
- double d=33.4;
- pw.println(i);
- pw.println(d);
- }
- }
- 使用字符流的文件IO
- 使用FileWriter
- FileWriter創建了一個可以用於寫入文件的writer,它的常用構造函數是:
- FileWriter(String filename) throws IOException
- FileWriter(String filename,boolean append) throws IOException
- import java.io.*;
- class javadir{
- public static void main(String args[]){
- String s;
- FileWriter fw;
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- try{
- fw=new FileWriter("t.txt");
- }catch(IOException exc){
- System.out.println("Can not Open");
- return;
- }
- System.out.println("Enter text('stop' to quit)");
- try{
- do{
- s=br.readLine();
- if(s.compareTo("stop")==0) break;
- s=s+"\r\n";
- fw.write(s);
- }while(s.compareTo("stop")!=0);
- }catch(IOException exc){
- System.out.println("Error writing file");
- }
- try{
- fw.close();
- }catch(IOException exc){
- System.out.println("Error closing file");
- }
- }
- }
- 使用FileReader
- FileReader創建了一個用於讀取文件內容的Reader ,它最常用的構造函數是:
- FileReader(String filename) throws FileNotFoundException
- import java.io.*;
- class javadir{
- public static void main(String args[]) throws Exception {
- String s;
- FileReader fr;
- BufferedReader br;
- PrintWriter pw=new PrintWriter(System.out,true);
- try{
- fr=new FileReader("t.txt");
- br=new BufferedReader(fr);
- }catch(FileNotFoundException exc){
- pw.println("Can not Open");
- return;
- }
- try{
- while((s=br.readLine())!=null){
- pw.println(s);
- }
- }catch(IOException exc){
- pw.println("Error reading file");
- }
- try{
- fr.close();
- }catch(IOException exc){
- pw.println("Error ");
- }
- }
- }
- 如果是關於字符流讀取的話,用BufferedReader實現