標籤:writer 建立檔案 輸出資料流 遍曆檔案 報錯 cep font 存在 tco
<!--位元組流 寫 -->
public class WriterDemo { public static void main(String[] args) { //執行個體化檔案對象,檔案不存在會自動建立,目錄不存在會報錯 File file = new File("src/檔案位元組流輸入輸出/text.txt"); try { //執行個體化檔案流對象(參數:檔案對象,是否追加,true向檔案追加資料,false覆蓋資料) FileOutputStream outputStream = new FileOutputStream(file,true); for(int i = 0; i < 5; i++){ outputStream.write("huangweiqiang\n".getBytes()); } outputStream.close(); } catch (Exception e) { System.out.println("建立檔案流失敗"); } }}
<!--位元組流 讀 -->
public class ReadeDemo { public static void main(String[] args) { // 執行個體化檔案對象 File file = new File("src/檔案位元組流輸入輸出/text.txt"); try { // 開機檔案流 FileInputStream fileInputStream = new FileInputStream(file); // 迴圈遍曆檔案中的每一個位元組 // 依次擷取檔案中的位元組 : i = fileInputStream.read() for (int i = fileInputStream.read(); i >= 0; i = fileInputStream.read()) { System.out.print((char) i); } // 關閉檔案流 fileInputStream.close(); } catch (Exception e) { System.out.println("檔案流建立失敗"); } }}
<!--位元組流實現檔案拷貝-->
public class CopyDemo { public static void main(String[] args) { // 建立檔案對象 File f1 = new File("src/檔案位元組流輸入輸出/text.txt"); File f2 = new File("src/檔案位元組流輸入輸出/textCopy.txt"); try ( // 建立輸入輸出資料流(java1.7開始在這裡面的代碼會自動關閉) InputStream inputStream = new FileInputStream(f1); OutputStream outputStream = new FileOutputStream(f2); ){ // 聲明緩衝數組 byte[] b = new byte[1024]; // 聲明擷取位元組變數的個數 int len = -1; while ((len = inputStream.read(b)) != -1) { // 將讀取到的位元組數組寫入目標檔案 outputStream.write(b, 0, len); } } catch (Exception e) { // 輸出異常資訊 e.printStackTrace(); } }}
JAVA IO ( 位元組流輸入輸出 )