Skip to content

Latest commit

 

History

History
68 lines (49 loc) · 1.23 KB

字節流.md

File metadata and controls

68 lines (49 loc) · 1.23 KB

字節流

演示

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ByteStreamDemo {

	public static void main(String[] args) throws IOException {

		demo_write();
		demo_read();
	}
	
	public static void demo_read() throws IOException {

		//1. 創建一個讀取流對象
		FileInputStream fis = new FileInputStream("byteDemo.txt");
		
		byte[] buf = new byte[fis.available()];//讀取文件容量
		fis.read(buf);
		System.out.println(new String(buf));
		
		
		//建議使用這種方法
//		byte[] buf = new byte[1024];
//		int len = 0;
//		
//		while((len = fis.read()) != -1) {
//			
//			System.out.println(new String(buf, 0, len));
//		}
		
		
//		int ch = 0;
//		while((ch = fis.read()) != -1) {
//			
//			System.out.println((char) ch);
//		}
		
		//一次讀取 一個字節
//		int ch = fis.read();
//		System.out.println(ch);
		
		fis.close();
	}

	public static void demo_write() throws IOException {
		
		//1. 創建字節輸出流對象,用於操作文件
		FileOutputStream fos = new FileOutputStream("byteDemo.txt"); 	
		
		//2. 寫數據,直接寫入到目的地中
		fos.write("abcdef".getBytes());
		
//		fos.flush();
		fos.close();
	}

}

打印結果

abcdef