【IO流】FileInputStream,FileOutputStream讀寫文件

FileInputStream,FileOutputStream(文件字節輸入輸出流)讀寫文件

注:IO流使用完之後 記得關閉,釋放資源

/**
 * FileOutputStream FileInputStream Test
 * 
 * @author xiazhang
 * @date   2017-6-4
 */
public class FileOutInputStreamTest {

	/**
	 * 讀文件
	 */
	private static void readFile(File file){
		try {
			FileInputStream fis = new FileInputStream(file);
			
			//每次讀取一個字節
			/*int content = fis.read();
			//content != -1 表示讀到結束的標記
			while(content != -1){
				System.out.print((char)content);
				content = fis.read();
			}*/
			
			
			/*int num = 1;//讀取次數
			byte[] b = new byte[20];
			//從此輸入流中將最多 b.length 個字節的數據讀入一個 byte 數組中
			//每次讀取20個字節到byte數組中
			//返回的int表示讀到此數組中的實際長度
			int len = fis.read(b);
			while(len != -1){
				System.out.print(new String(b,0,len));
				len = fis.read(b);
				if(len != -1){
					num++;
				}
			}
			//結果:共讀取5次
			System.out.println("讀取次數:"+num);*/
			
			
			
			int num = 1;//讀取次數
			byte[] b = new byte[20];
			//從此輸入流中將最多 5 個字節的數據讀入一個 byte 數組中
			int len = fis.read(b, 1, 5);
			while(len != -1){
				System.out.println(new String(b,1,len));
				len = fis.read(b, 1, 5);
				if(len != -1){
					num ++;
				}
			}
			//結果:共讀取17次
			System.out.println("讀取次數:"+num);
			
			//流必須關閉  釋放資源
			fis.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 寫入文件
	 */
	private static void writeFile(File file){ 
		try {
			FileOutputStream fos = new FileOutputStream(file);
			//寫入字節
			fos.write(97);
			fos.write(98);
			fos.write(99);
			//關閉流  釋放資源
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
		}
	}
	
	
	
	public static void main(String[] args) {
		File file = new File("fileTest3.txt");
		if(!file.exists()){//檢查文件是否存在
			/*try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
			System.out.println(file.getName()+"不存在!");
		}else{
			readFile(file);
			writeFile(file);
		}
		
	}

}








發佈了27 篇原創文章 · 獲贊 17 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章