天天看點

java寫檔案讀寫操作(IO流,位元組流)

package copyfile;

import java.io.*;

public class copy {
	public static void main(String[] args) throws IOException {
		 copyFile("d:/new/a.txt","d:/new/b.txt",true);//oldpath,newpath,是否不覆寫前文
	}
	public static void copyFile(String oldpth,String newpath,boolean add) throws IOException{
		FileInputStream in = null;
		FileOutputStream fs = null;
		try {
			//執行個體化檔案,并判斷檔案是否存在
			File oldfile=new File(oldpth);
			if(oldfile.exists()){
					//初始化檔案輸入與輸出流
					in=new FileInputStream(oldpth);
					fs=new FileOutputStream(newpath,add);
					//定義存放讀取資料的數組
					byte[] buffer=new byte[10];
					int length;
					while(true){
						int len=in.read(buffer);//當檔案讀完,傳回-1,否則傳回讀取檔案長度
												/*注:輸出讀取的目前檔案内容方法
												 * String s=new String(buffer);
												 * s.trim();(去除字元串前後兩端的空格)
												*/
						if(len==-1)break;
						fs.write(buffer);
					}
					System.out.println("OK");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			in.close();
			fs.close();
		}
	}
}
      

/**

* IO流的資料寫入和讀取

* 在本質上是用的FileReader("c:text.txt")或FileWriter("c:text2.txt")

* 通過read()或write()讀取或寫入單個字元存入資料中

* 由于操作起來比較麻煩效率不高。是以後來引入了緩沖流的概念,

* 是以出現了BufferedReader對象,通過這個對象,将fileRead讀取的資料進行緩沖

* 提高效率

* */