IO流第四課位元組輸出流和字元輸出流
阿新 • • 發佈:2018-11-12
這節課講位元組輸出流和字元輸出流
輸出流和輸入流差不多,只不過輸入流是讀取檔案內容,輸出流是向檔案中寫入內容
直接看Demo吧:
Demo1: 通過位元組輸出流寫入檔案
public static void main(String[] args) { File file = new File("F:\\code\\java\\output.txt"); //還沒有這個檔案 OutputStream os =null; try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } try { os =new FileOutputStream(file); String content = "OutputStream"; byte[] bytes = content.getBytes(); os.write(bytes); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try{ if (os != null) os.close(); } catch (IOException e) { e.printStackTrace(); } } }
Demo2: 字元輸出流寫入檔案
public static void main(String[] args) { File file = new File("F:\\code\\java\\writer.txt"); //這個檔案顯然不存在 Writer writer = null; try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } try { writer= new PrintWriter(file); String content = "Writer"; writer.write(content); //這裡可以直接傳String型別, // 看底層原始碼可以發現實際上還是講content轉換成char[],然後呼叫writer.write(char cbuf[], int off, int len) } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (writer != null) writer.close(); } catch (IOException e) { e.printStackTrace(); } } }