轉載於:http://www.javashuo.com/article/p-ugzbenge-do.htmlhtml
1、Java把這些不一樣來源和目標的數據都統一抽象爲數據流。java
Java語言的輸入輸出功能是十分強大而靈活的。緩存
在Java類庫中,IO部分的內容是很龐大的,由於它涉及的領域很普遍:標準輸入輸出,文件的操做,網絡上的數據流,字符串流,對象流,zip文件流。網絡
這裏介紹幾種讀寫文件的方式post
2、InputStream、OutputStream(字節流)htm
//讀取文件(字節流) InputStream in = new FileInputStream("d:\\1.txt"); //寫入相應的文件 OutputStream out = new FileOutputStream("d:\\2.txt"); //讀取數據 //一次性取多少字節 byte[] bytes = new byte[2048]; //接受讀取的內容(n就表明的相關數據,只不過是數字的形式) int n = -1; //循環取出數據 while ((n = in.read(bytes,0,bytes.length)) != -1) { //轉換成字符串 String str = new String(bytes,0,n,"GBK"); #這裏能夠實現字節到字符串的轉換,比較實用 System.out.println(str); //寫入相關文件 out.write(bytes, 0, n); } //關閉流 in.close(); out.close();
3、BufferedInputStream、BufferedOutputStream(緩存字節流)使用方式和字節流差很少,可是效率更高(推薦使用)對象
//讀取文件(緩存字節流) BufferedInputStream in = new BufferedInputStream(new FileInputStream("d:\\1.txt")); //寫入相應的文件 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("d:\\2.txt")); //讀取數據 //一次性取多少字節 byte[] bytes = new byte[2048]; //接受讀取的內容(n就表明的相關數據,只不過是數字的形式) int n = -1; //循環取出數據 while ((n = in.read(bytes,0,bytes.length)) != -1) { //轉換成字符串 String str = new String(bytes,0,n,"GBK"); System.out.println(str); //寫入相關文件 out.write(bytes, 0, n); } //清楚緩存 out.flush(); //關閉流 in.close(); out.close();
4、InputStreamReader、OutputStreamWriter(字符流,這種方式不建議使用,不能直接字節長度讀寫)。使用範圍用作字符轉換blog
//讀取文件(字節流) InputStreamReader in = new InputStreamReader(new FileInputStream("d:\\1.txt"),"GBK"); //寫入相應的文件 OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("d:\\2.txt")); //讀取數據 //循環取出數據 byte[] bytes = new byte[1024]; int len = -1; while ((len = in.read()) != -1) { System.out.println(len); //寫入相關文件 out.write(len); } //清楚緩存 out.flush(); //關閉流 in.close(); out.close();
5、BufferedReader、BufferedWriter(緩存流,提供readLine方法讀取一行文本)ip
//讀取文件(字符流) BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("d:\\1.txt"),"GBK"));#這裏主要是涉及中文 //BufferedReader in = new BufferedReader(new FileReader("d:\\1.txt"))); //寫入相應的文件 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:\\2.txt"),"GBK")); //BufferedWriter out = new BufferedWriter(new FileWriter("d:\\2.txt")); //讀取數據 //循環取出數據 String str = null; while ((str = in.readLine()) != null) { System.out.println(str); //寫入相關文件 out.write(str); out.newLine(); } //清楚緩存 out.flush(); //關閉流 in.close(); out.close();
6、Reader、PrintWriter(PrintWriter這個很好用,在寫數據的同事能夠格式化)字符串
//讀取文件(字節流) Reader in = new InputStreamReader(new FileInputStream("d:\\1.txt"),"GBK"); //寫入相應的文件 PrintWriter out = new PrintWriter(new FileWriter("d:\\2.txt")); //讀取數據 //循環取出數據 byte[] bytes = new byte[1024]; int len = -1; while ((len = in.read()) != -1) { System.out.println(len); //寫入相關文件 out.write(len); } //清楚緩存 out.flush(); //關閉流 in.close(); out.close();
7、基本的幾種用法就這麼多,固然每個讀寫的使用都是能夠分開的。爲了更好的來使用io。流裏面的讀寫,建議使用BufferedInputStream、BufferedOutputStream