2-字节流
package com.io;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;import org.junit.Test;
/*** * @author Administrator*1、流的分類*(1)按照數據流向的不同,分為輸入流和輸出流*(2)按照處理數據單位的不同,分為字節流和字符流*(3)按照角色的不同,分為節點流(直接作用于文件,所有帶File的InputStream OutputStream)、處理流(作用于節點流上面,提高效率)*2、IO體系*抽象基類 節點流(即文件流) 緩總流(處理流的一種)*InputStream FileInputStream BufferedInputStream*OutputStream FileOutputStream BufferedOutputStream*Reader FileReader BufferedReader*Writer FileWriter BufferedWriter*3、所有的處理流都作用于上面四種節點流,才能進行對文件操作*/
public class FileInputOurPutStreamTest {/*** 每次讀一個字節*/@Testpublic void fileInputStreamTest1(){FileInputStream fis = null;//1、先創建file對象try { //有異常在這里捕獲,因為fis使用完后一定要關閉File file1 = new File("hello1.txt");//2、創建FileInputStream對象fis = new FileInputStream(file1);/**int b = fis.read();//read方法,一次讀取一個字節,讀到文件最后返回-1while(b != -1){
// System.out.println(b);//因為讀取的是字節,這里用int接收,所以打印出來是unicode碼,要顯示字母,加char強制轉化System.out.println((char)b);b = fis.read();}**///上面代碼可以簡寫成int b ;while( (b = fis.read()) != -1 ){System.out.print((char)b);}} catch ( IOException e) {e.printStackTrace();}finally{try {fis.close();} catch (IOException e) {e.printStackTrace();}}}/*** 每次讀一個數組長度的字節*/@Testpublic void fileInputStreamTest2(){File file = new File("hello1.txt");FileInputStream fis = null;try{fis = new FileInputStream(file);byte[] b = new byte[5];int len;//len是每次讀出放到數組中的字節數,當到文件末尾的時候返回-1,前幾個len都返回的是數組的長度,最后一個返回的len<=數組長度StringBuffer strTmp = new StringBuffer("");while( (len = fis.read(b)) != -1 ){System.out.println(len);String str = new String(b, 0, len);//這里要注意new String的三個參數,第一個是數組,第二個是從數組的第幾個下標開始讀,最后一個,是最后一個數組的長度
System.out.println(str);strTmp.append(str);}System.out.println("strTmp-===" + strTmp);}catch(Exception e){e.printStackTrace();}finally{try {fis.close();} catch (IOException e) {e.printStackTrace();}}}@Testpublic void fileOutPutStreamTest(){File file = new File("hello_out.txt");FileOutputStream fos = null;try{fos = new FileOutputStream(file);byte[] strTmp = new String("I love china").getBytes();fos.write(strTmp);}catch(Exception e){e.printStackTrace();}finally{try {fos.close();} catch (IOException e) {e.printStackTrace();}}}/*** 從一個文件讀取內容,寫入到另外一個文件* 即文件的復制*/@Testpublic void fileInputOutputStreamTest(){FileInputStream fis = null;FileOutputStream fos = null;File fileIn = new File("hello1.txt");File fileout = new File("hello2.txt");try{fis = new FileInputStream(fileIn);fos = new FileOutputStream(fileout);int len;byte [] b = new byte[20];//根據文件大小來設定數組的大小while((len = fis.read(b)) != -1){fos.write(b, 0, len);//0是從字節數組b的的第0位開始
}}catch(Exception e){e.printStackTrace();}finally{try {fis.close();} catch (IOException e) {e.printStackTrace();}try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}
?
轉載于:https://www.cnblogs.com/fubaizhaizhuren/p/5026116.html
總結
- 上一篇: JNI基础 c语言调用java方法
- 下一篇: KVO