1. 程式人生 > >java中io流詳細整理

java中io流詳細整理

       Java.io包中最重要的就是5個類和一個介面。5個類指的是File、OutputStream、InputStream、Writer、Reader;一個介面指的是Serializable。掌握了這些就掌握了Java I/O的精髓了。

Java I/O主要包括如下3層次:

  1. 流式部分——最主要的部分。如:OutputStream、InputStream、Writer、Reader等
  2. 非流式部分——如:File類、RandomAccessFile類和FileDescriptor等類
  3. 其他——檔案讀取部分的與安全相關的類,如:SerializablePermission類,以及與本地作業系統相關的檔案系統的類,如:FileSystem類和Win32FileSystem類和WinNTFileSystem類。

主要類如下:

  1. File(檔案特徵與管理):用於檔案或者目錄的描述資訊,例如生成新目錄,修改檔名,刪除檔案,判斷檔案所在路徑等。
  2. InputStream(位元組流,二進位制格式操作):抽象類,基於位元組的輸入操作,是所有輸入流的父類。定義了所有輸入流都具有的共同特徵。
  3. OutputStream(位元組流,二進位制格式操作):抽象類。基於位元組的輸出操作。是所有輸出流的父類。定義了所有輸出流都具有的共同特徵。
  4. Reader(字元流,文字格式操作):抽象類,基於字元的輸入操作。
  5. Writer(字元流,文字格式操作):抽象類,基於字元的輸出操作。
  6. RandomAccessFile(隨機檔案操作):它的功能豐富,可以從檔案的任意位置進行存取(輸入輸出)操作

I:O體系.png

I/O流

java.io包裡有4個基本類:InputStream、OutputStream及Reader、Writer類,它們分別處理位元組流和字元流。

其他各種各樣的流都是由這4個派生出來的。

I/O流

按來源/去向分類:

  1. File(檔案): FileInputStream, FileOutputStream, FileReader, FileWriter
  2. byte[]:ByteArrayInputStream, ByteArrayOutputStream
  3. Char[]: CharArrayReader, CharArrayWriter
  4. String: StringBufferInputStream, StringReader, StringWriter
  5. 網路資料流:InputStream, OutputStream, Reader, Writer

InputStream

InputStream 為位元組輸入流,它本身為一個抽象類,必須依靠其子類實現各種功能,此抽象類是表示位元組輸入流的所有類的超類。 繼承自InputStream 的流都是向程式中輸入資料的,且資料單位為位元組(8bit);

InputStream是輸入位元組資料用的類,所以InputStream類提供了3種過載的read方法.Inputstream類中的常用方法:

  • public abstract int read( ):讀取一個byte的資料,返回值是高位補0的int型別值。若返回值=-1說明沒有讀取到任何位元組讀取工作結束。
  • public int read(byte b[ ]):讀取b.length個位元組的資料放到b陣列中。返回值是讀取的位元組數。該方法實際上是呼叫下一個方法實現的
  • public int read(byte b[ ], int off, int len):從輸入流中最多讀取len個位元組的資料,存放到偏移量為off的b陣列中。
  • public int available( ):返回輸入流中可以讀取的位元組數。注意:若輸入阻塞,當前執行緒將被掛起,如果InputStream物件呼叫這個方法的話,它只會返回0,這個方法必須由繼承InputStream類的子類物件呼叫才有用,
  • public long skip(long n):忽略輸入流中的n個位元組,返回值是實際忽略的位元組數, 跳過一些位元組來讀取
  • public int close( ) :使用完後,必須對我們開啟的流進行關閉。

來看看幾種不同的InputStream:

  1. FileInputStream把一個檔案作為InputStream,實現對檔案的讀取操作
  2. ByteArrayInputStream:把記憶體中的一個緩衝區作為InputStream使用
  3. StringBufferInputStream:把一個String物件作為InputStream
  4. PipedInputStream:實現了pipe的概念,主要線上程中使用
  5. SequenceInputStream:把多個InputStream合併為一個InputStream

OutputStream

OutputStream提供了3個write方法來做資料的輸出,這個是和InputStream是相對應的。

  • public void write(byte b[ ]):將引數b中的位元組寫到輸出流。
  • public void write(byte b[ ], int off, int len) :將引數b的從偏移量off開始的len個位元組寫到輸出流。
  • public abstract void write(int b) :先將int轉換為byte型別,把低位元組寫入到輸出流中。
  • public void flush( ) : 將資料緩衝區中資料全部輸出,並清空緩衝區。
  • public void close( ) : 關閉輸出流並釋放與流相關的系統資源。

幾種不同的OutputStream:

  1. ByteArrayOutputStream:把資訊存入記憶體中的一個緩衝區中
  2. FileOutputStream:把資訊存入檔案中
  3. PipedOutputStream:實現了pipe的概念,主要線上程中使用
  4. SequenceOutputStream:把多個OutStream合併為一個OutStream

Reader和InputStream類似;Writer和OutputStream類似。

有兩個需要注意的:

  1. InputStreamReader : 從輸入流讀取位元組,在將它們轉換成字元。
  2. BufferReader :接受Reader物件作為引數,並對其新增字元緩衝器,使用readline()方法可以讀取一行。

如何選擇I/O流

  1. 確定是輸入還是輸出
    輸入:輸入流 InputStream Reader
    輸出:輸出流 OutputStream Writer
  2. 明確操作的資料物件是否是純文字
    是:字元流 Reader,Writer
    否:位元組流 InputStream,OutputStream
  3. 明確具體的裝置。
    • 檔案:
      讀:FileInputStream,, FileReader,
      寫:FileOutputStream,FileWriter
    • 陣列:
      byte[ ]:ByteArrayInputStream, ByteArrayOutputStream
      char[ ]:CharArrayReader, CharArrayWriter
    • String:
      StringBufferInputStream(已過時,因為其只能用於String的每個字元都是8位的字串), StringReader, StringWriter
    • Socket流
      鍵盤:用System.in(是一個InputStream物件)讀取,用System.out(是一個OutputStream物件)列印
  4. 是否需要轉換流
    是,就使用轉換流,從Stream轉化為Reader、Writer:InputStreamReader,OutputStreamWriter
  5. 是否需要緩衝提高效率
    是就加上Buffered:BufferedInputStream, BufferedOuputStream, BufferedReader, BufferedWriter
  6. 是否需要格式化輸出

一下面先說說FIle類:

FIle中常用的方法:

1.建立
 boolean createNewFile();在指定路徑建立檔案,如果檔案已經存在,則不建立,返回false.輸出流
                         物件一旦建立,如果檔案存在,則會覆蓋。
 boolean mkdir():建立一級資料夾

 boolean mkdirs():建立多級資料夾

2.刪除
    boolean delete():刪除失敗返回false。如果檔案正在使用,則刪除不了返回false

    void deleteOnExit():程式退出時刪除檔案

3.判斷
    boolean exists():判斷檔案是否存在
    isFile();//測試此抽象路徑名錶示的檔案是否是一個標準文
    isDirectory();//是否是目錄
    isHidden();
 4.獲取資訊
 getName();
 getPath();//獲取路徑
 getAbsoluteFile();//獲取絕對路徑封裝成檔案物件
 getAbsolutPath();//獲取絕對路徑
 getParent();//該方法返回的是絕對路徑中的父目錄,如果獲取的是相對路徑,返回null.
 lastModified();
 length();

例子:

建立一個新檔案

package www.xxx.com;

import java.io.File;
import java.io.IOException;

public class Hello {
           public static void main(String[] args) throws IOException {
        	     String filename="E:"+File.separator+"xie"+File.separator+"text.txt";
        	     File f=new File(filename);
        	     if(!f.exists()){ 	 
						f.createNewFile(); 
        	     }     
           }
}

刪除一個檔案

package www.xxx.com;

import java.io.File;
import java.io.IOException;

public class Hello {
           public static void main(String[] args) throws IOException {
        	     String filename="E:"+File.separator+"xie"+File.separator+"text.txt";
        	     File f=new File(filename);
        	     if(f.exists()){
        	    	f.delete(); 
        	     }else{
        	    	 System.out.println("不存在此檔案");
        	     }     
           }
}

建立一個資料夾

package www.xxx.com;

import java.io.File;
import java.io.IOException;

public class Hello {
           public static void main(String[] args) throws IOException {
        	     String filename="E:"+File.separator+"xie"+File.separator+"hello";
        	     File f=new File(filename);
        	     f.mkdir();     
           }
}

列出指定目錄的全部檔案(包括隱藏檔案):

package www.xxx.com;

import java.io.File;
import java.io.IOException;

public class Hello {
           public static void main(String[] args) throws IOException {
        	     String filename="E:"+File.separator+"xie"+File.separator+"hello";
        	     File f=new File(filename);
        	     if(!f.exists()){
        	    	 f.createNewFile();
        	     }
        	     String[] fb=f.list();
        	     for(String str:fb){
        	    	 System.out.println(str);
        	     }
           }
}
執行結果:ddd
新建文字文件.txt
如果要檔案全路徑:
package www.xxx.com;

import java.io.File;
import java.io.IOException;

public class Hello {
           public static void main(String[] args) throws IOException {
        	     String filename="E:"+File.separator+"xie"+File.separator+"hello";
        	     File f=new File(filename);
        	     if(!f.exists()){
        	    	 f.createNewFile();
        	     }
        	     File[] fhs=f.listFiles();
        	     for(File fh:fhs){
        	    	 System.out.println(fh);
        	     }
           }
}

執行結果:

E:\xie\hello\ddd

E:\xie\hello\新建文字文件.txt

判斷一個指定的路徑是否為目錄:

package www.xxx.com;

import java.io.File;
import java.io.IOException;

public class Hello {
           public static void main(String[] args) throws IOException {
        	     String filename="E:"+File.separator+"xie"+File.separator+"hello";
        	     File f=new File(filename);
        	     if(f.exists()){
        	    	 f.createNewFile();
        	     }
        	     if(f.isDirectory()){
        	    	 System.out.println("yes");
        	     }else{
        	    	 System.out.println("no");
        	     }
           }
}

執行結果:

yes

使用RandomAccessFile寫入檔案

package www.xxx.com;

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

public class Hello {
           public static void main(String[] args) throws IOException {
        	     String filename="E:"+File.separator+"xie"+File.separator+"Test.txt";
        	     File f=new File(filename);
        	     if(!f.exists()){
        	    	 f.createNewFile();
        	     }
        	     RandomAccessFile dom=new RandomAccessFile(f,"rw");
        	     dom.write("fdsfssdf多付費方式等".getBytes());
        	     dom.writeBytes("dsafdas");
        	     dom.writeChar('A');
        	     dom.close();
           }
}

執行結果:

開啟檔案有寫入,不過是亂碼

下面說說RandomAccessFile的簡單用法

RandomAccessFile類的常用的操作方法1、public  RandomAccessFile(File file, String mode)throws FileNotFoundException  構造方法  接收File類的物件,指定操作路徑,但是在設定時需要設定模式:"r": 只讀、"w": 只寫、"rw": 讀寫。2、public RandomAccessFile(String name, String mode) throws FileNotFoundException 構造方法 不再使用File類物件表示檔案,而是直接輸入了一個固定的檔案路徑。3、public void close() throws IOException   關閉操作4、public int read(byte[] b) throws IOException 將內容讀取到一個byte陣列之中5、public final byte readByte()  throws IOException 讀取一個位元組6、public final int readInt()  throws IOException從檔案中讀取整型資料。7、public void seek(long pos) throws IOException 設定讀指標的位置。8、public final void writeBytes(String s) throws IOException 將一個字串寫入到檔案之中,按位元組的方式處理。9、public final void writeInt(int v) throws IOException 將一個int型資料寫入檔案,長度為4位。10、public int skipBytes(int n) throws IOException 指標跳過多少個位元組。構造:public RandomAccessFile(File file, String mode)  throws FileNotFoundException例項化此類的時候需要傳遞File類,告訴程式應該操作的是哪個檔案,之後有一個模式,檔案的開啟模式,常用的兩種模式:r:讀模式w:只寫rw:讀寫,如果使用此模式,如果此檔案不存在,則會自動建立。

例子:在檔案中寫入

zhangsan,11

lisi,12

waner,15

package www.xxx.com;




import java.io.File;
import java.io.RandomAccessFile;




public class Hello {
           public static void main(String[] args) throws Exception {
        	   String fp="E:"+File.separator+"xie"+File.separator+"Test.txt";
               File f=new File(fp);
        	     RandomAccessFile rdaf = null ;       // 宣告RandomAccessFile類的物件  
        	     rdaf=new RandomAccessFile(f,"rw");//讀寫,如果使用此模式,此檔案不存在時,則會自動建立
        	     String name=null;
        	     int age=0;
        	     name="zhangsan";//字串的長度為8
        	     age=11;
        	     rdaf.writeBytes(name);//將名字寫入檔案中
        	     rdaf.writeInt(age);//數字長度為4,將年齡寫入檔案中
        	     name="lisi    ";
        	     age=12;
        	     rdaf.writeBytes(name);
        	     rdaf.writeInt(age);
        	     name="wanger  ";
        	     age=15;
        	     rdaf.writeBytes(name);
        	     rdaf.writeInt(age);
        	     rdaf.close();
           }
}

讀取檔案:

package www.xxx.com;

import java.io.File;
import java.io.RandomAccessFile;


public class Hello {
           public static void main(String[] args) throws Exception {
        	     String fp="E:"+File.separator+"xie"+File.separator+"Test.txt";
        	     File f=new File(fp);
        	     RandomAccessFile rdaf=null;     // 宣告RandomAccessFile類的物件  
        	     rdaf=new RandomAccessFile(f,"r");//只讀
        	     int age=0;
        	     byte b[]=new byte[8];
        	     String name=null;
        	     //我們先讀取第二個人資訊
        	     rdaf.skipBytes(12);//跳過第一個人的資訊
        	     for(int i=0;i<b.length;i++){
        	    	 b[i]=rdaf.readByte();//讀取一個位元組
        	     }
        	     name=new String(b);//轉化為字串
        	     age=rdaf.readInt();//讀取年齡
        	     System.out.println("第二個人的資訊-->name:"+name+",age:"+age);
        	     //讀取第一個人的資訊
        	     rdaf.seek(0);//指標跳轉到第一個人資訊
        	     for(int i = 0;i<b.length;i++){
        	    	 b[i]=rdaf.readByte();
        	     }
        	     name=new String(b);
        	     age=rdaf.readInt();
        	     System.out.println("第一個人的資訊-->name:"+name+",age:"+age);
        	     //讀取第三個人資訊
        	     rdaf.skipBytes(12);//跳過第二個人得資訊
        	     for(int i=0;i<b.length;i++){
        	    	 b[i]=rdaf.readByte();
        	     }
        	     name=new String(b);
        	     age=rdaf.readInt();
        	     System.out.println("第三個人的資訊-->name:"+name+",age:"+age);
        	     rdaf.close();
           }
}


執行結果:

第二個人的資訊-->name:lisi    ,age:12
第一個人的資訊-->name:zhangsan,age:11

第三個人的資訊-->name:wanger  ,age:15

二:File(檔案): FileInputStream, FileOutputStream, FileReader, FileWriter

FileInputStream讀資料:
package www.xxx.com;

import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;

public class Hello {
           public static void main(String[] args) throws Exception {
        	    String path="E:"+File.separator+"xie"+File.separator+"text.txt";
        	    FileInputStream fis=new FileInputStream(path);
        	    int len=fis.available();
        	    byte[] bt=new byte[len];
        	    fis.read(bt);
        	    String str=new String(bt);
        	    System.out.println(str); 
                    fis.close();    
           }
}

FileOutputStream寫資料:    

package www.xxx.com;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;

public class Hello {
           public static void main(String[] args) throws Exception {
        	    String path="E:"+File.separator+"xie"+File.separator+"text.txt";
        	    FileOutputStream fos=new FileOutputStream(path);
        	    String content="張三123";
        	    byte[] bt=content.getBytes();////將字串轉成位元組陣列
        	    fos.write(bt);//將引數bt中的位元組寫到輸出流
        	    fos.flush();//將資料緩衝區中資料全部輸出,並清空緩衝區。
        	    fos.close(); 
           }
}

3,FileReader類

1,構造方法

FileReader fr = new FileReader(String fileName);//使用帶有指定檔案的String引數的構造方法。建立該輸入流物件。並關聯原始檔。

2,主要方法

int read(); // 讀取單個字元。返回作為整數讀取的字元,如果已達到流末尾,則返回 -1。

int read(char []cbuf);//將字元讀入陣列。返回讀取的字元數。如果已經到達尾部,則返回-1。

void close();//關閉此流物件。釋放與之關聯的所有資源。

FileReader 讀取檔案例子:

package www.xxx.com;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.RandomAccessFile;

public class Hello {
           public static void main(String[] args) throws Exception {
        	    String path="E:"+File.separator+"xie"+File.separator+"text.txt";
        	    FileReader fr=new FileReader(path);
        	    int ch=0;
        	    while((ch=fr.read())!=-1){
        	    	System.out.print((char)ch);
        	    	
        	    }
        	    fr.close();
           }
}

4,FileWriter類(字元輸出流類)

構造方法:FileWriter fw = new FileWriter(String fileName);//建立字元輸出流類物件和已存在的檔案相關聯。檔案不存在的話,並建立。

                                             如:FileWriter fw = new FileWriter("C:\\demo.txt");

             FileWriter fw = new FileWriter(String fileName,boolean append);//建立字元輸出流類物件和已存在的檔案相關聯,並設定該該流對檔案的操作是否為續寫。

                                             如:FileWriter fw = new FileWriter("C:\\demo.txt",true); //表示在fw對檔案再次寫入時,會在該檔案的結尾續寫,並不會覆蓋掉。

主要方法: void write(String str)   //寫入字串。當執行完此方法後,字元資料還並沒有寫入到目的檔案中去。此時字元資料會儲存在緩衝區中。

               此時在使用重新整理方法就可以使資料儲存到目的檔案中去。

                  viod flush()                //重新整理該流中的緩衝。將緩衝區中的字元資料儲存到目的檔案中去。

                  viod close()               //關閉此流。在關閉前會先重新整理此流的緩衝區。在關閉後,再寫入或者重新整理的話,會拋IOException異常。

例子:

package www.xxx.com;

import java.io.File;
import java.io.FileWriter;

public class Hello {
           public static void main(String[] args) throws Exception {
        	    String path="E:"+File.separator+"xie"+File.separator+"text.txt";
		    FileWriter fw=new FileWriter(path,true);
        	    String str="字串12343";
        	    fw.write(str);
        	    fw.flush();//重新整理該流中的緩衝。將緩衝區中的字元資料儲存到目的檔案中去。
        	    fw.close();   
           }
}

FileInputStream類與FileReader類的區別:

FileInputStream:以位元組流方式讀取;FileReader:把檔案轉換為字元流讀入; 

 InputStream提供的是位元組流的讀取,而非文字讀取,這是和Reader類的根本區別。用Reader讀取出來的是char陣列或者String ,使用InputStream讀取出來的是byte陣列。 
 Reader類及其子類提供的字元流的讀取char(16位,unicode編碼),inputStream及其子類提供位元組流的讀取byte(8位),所以FileReader類是將檔案按字元流的方式讀取,FileInputStream則按位元組流的方式讀取檔案;InputStreamReader 可以將讀如stream轉換成字元流方式,是reader和stream之間的橋樑 
 最初Java是不支援對文字檔案的處理的,為了彌補這個缺憾而引入了Reader和Writer兩個類。 
 FileInputStream類以二進位制輸入/輸出,I/O速度快且效率搞,但是它的read()方法讀到的是一個位元組(二進位制資料),很不利於人們閱讀。 

 而FileReader類彌補了這個缺陷,可以以文字格式輸入/輸出,非常方便;比如可以使用while((ch = filereader.read())!=-1)

另補充:

迴圈來讀取檔案;可以使用BufferedReader的readLine()方法一行一行的讀取文字。 

當我們讀寫文字檔案的時候,採用Reader是非常方便的,比如FileReader, InputStreamReader和BufferedReader。其中最重要的類是InputStreamReader,它是位元組轉換為字元的橋樑。你可以在構造器重指定編碼的方式,如果不指定的話將採用底層作業系統的預設編碼方式,例如GBK等。 

 FileReader與InputStreamReader涉及編碼轉換(指定編碼方式或者採用os預設編碼),可能在不同的平臺上出現亂碼現象!而FileInputStream以二進位制方式處理,不會出現亂碼現象. 

使用BufferedReader的readLine()方法讀取檔案

package www.xxx.com;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;


public class Hello {
           public static void main(String[] args) throws Exception {
        	    String path="E:"+File.separator+"xie"+File.separator+"text.txt";
        	    FileInputStream fis=new FileInputStream(path);
        	    InputStreamReader isr=new InputStreamReader(fis);
        	    BufferedReader br=new BufferedReader(isr);
        	    String data=null;
        	    while((data=br.readLine())!=null){	
        	    	 System.out.println(data);
        	    }
        	    br.close();   
           }
}

一般檔案的讀取形式:

1) File file = new File ("hello.txt"); 
FileInputStream in=new FileInputStream(file); 

2) File file = new File ("hello.txt"); 
FileInputStream in=new FileInputStream(file); 
InputStreamReader inReader=new InputStreamReader(in); 
BufferedReader bufReader=new BufferedReader(inReader); 

3) File file = new File ("hello.txt"); 
FileReader fileReader=new FileReader(file); 
BufferedReader bufReader=new BufferedReader(fileReader);

陣列:

byte[ ]:ByteArrayInputStream, ByteArrayOutputStream

char[ ]:CharArrayReader, CharArrayWriter

package www.xxx.com;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Hello {
           public static void main(String[] args) throws Exception {
        	    String path="E:"+File.separator+"xie"+File.separator+"text.txt";
        	    FileInputStream fis=new FileInputStream(path);
        	    InputStreamReader isr=new InputStreamReader(fis);
        	    BufferedReader br=new BufferedReader(isr);
        	    String data=null;
        	    while((data=br.readLine())!=null){	
        	    	 System.out.println(data);
        	    }
        	    br.close();
        	   
           }
           private static void charArray() throws IOException {
   	        //字元陣列流/記憶體流
   	        //字元陣列輸出流:程式----->記憶體
   	        CharArrayWriter cw =new CharArrayWriter();
   	        cw.write("歡迎學習!");
   	        char[] content=cw.toCharArray();
   	        //位元組陣列輸入流:記憶體----->程式
   	        CharArrayReader reader=new CharArrayReader(content);
   	        int len=-1;
   	        char[] ch=new char[1024];
   	        while((len=reader.read(ch))!=-1){
   	            System.out.println(new String(ch,0,len));
   	        }
   	        cw.close();
   	        reader.close();
   	    }
   	 
   	    private static void byteArray() throws Exception {
   	        //位元組陣列流/記憶體流
   	        //位元組陣列輸出流:程式----->記憶體
   	        ByteArrayOutputStream out=new ByteArrayOutputStream();
   	        out.write("大家好啊!".getBytes());
   	        byte[] bye=out.toByteArray();
   	        //位元組陣列輸入流:記憶體----->程式
   	        ByteArrayInputStream in=new ByteArrayInputStream(bye);
   	        byte[] buffer=new byte[1024];
   	        int len=-1;
   	        while((len=in.read(buffer))!=-1){
   	            System.out.println(new String(buffer,0,len));
   	        }
   	        out.close();
   	        in.close();
   	    }
}

緩衝提高效率BufferedInputStream, BufferedOuputStream, BufferedReader, BufferedWriter

package www.xxx.com;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;


public class Hello {
           public static void main(String[] args) throws Exception {
        	    String path="E:"+File.separator+"xie"+File.separator+"text.txt";
        	    String writepath="E:"+File.separator+"xie"+File.separator+"text1.txt";
        	    InputStream is=new FileInputStream(path);
        	    BufferedInputStream bis=new BufferedInputStream(is);
        	    OutputStream os=new FileOutputStream(writepath);
        	    byte[] c=new byte[20];
        	    int len=0;
        	    while((len=bis.read(c))!=-1){
        	    	//把每次裝入桶中的內容寫入到檔案中,每次寫入0到len,因為len是每次讀取到的實際內容個數
        	    	os.write(c, 0, len);
        	    }
        	    os.flush();
        	    os.close();
        	    is.close();
        	    System.out.println("成功");
   	    }
}
檔案複製
package www.xxx.com;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

public class Hello {
           public static void main(String[] args) throws Exception {
        	    String path="E:"+File.separator+"xie"+File.separator+"text.txt";
        	    String writepath="E:"+File.separator+"xie"+File.separator+"text1.txt";
        	    Reader fiReader=new FileReader(path);
        	    BufferedReader bReader=new BufferedReader(fiReader);
        	    Writer fiw=new FileWriter(writepath);
        	    BufferedWriter bWriter=new BufferedWriter(fiw);
        	    String line=null;
        	    while((line=bReader.readLine())!=null){
        	    	System.out.println("line:"+line);////上面返回的line中的readLine方法中不包含換行符 
        	    	bWriter.write(line);
        	    	bWriter.newLine();////因為每次是讀取一行內容,所以顯示一行後就得換行 
        	    	bWriter.flush();
        	    }
        	    
        	    bWriter.close();
        	    fiReader.close();
   	    }
}