IO_標準步驟,位元組流
阿新 • • 發佈:2018-11-02
IO流操作的基標準步驟:
1:檔案位元組輸入流 (將檔案內容輸入到程式中)
public static void main(String[] args) { //1,建立源 File src = new File("abc.txt"); //2,選擇流 InputStream in = null; try { in = new FileInputStream(src); //3,操作(讀取) int temp=-1; while((temp=in.read())!=-1){ System.out.println((char)temp); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ //4.釋放資源 try { if(null == in){ in.close(); } } catch (IOException e) { e.printStackTrace(); } } }
我們還可以來個緩衝,一次性讀取多個位元組陣列。提高效率,
public static void main(String[] args) { File src = new File("abc.txt"); InputStream in = null; try { in = new FileInputStream(src); int temp=-1; byte[] flush = new byte[3]; while((temp = in.read(flush))!=-1){ String str = new String(flush,0,temp); System.out.print(str); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
2:檔案位元組輸出流 (將程式中的內容輸出到檔案中)
/** * 檔案位元組輸出流 (從程式輸出到檔案) * 1,建立源 * 2,選擇流 * 3,操作(寫出內容) * 4,釋放資源 */ public class IOTest04 { public static void main(String[] args) { //1,建立源 File dest = new File("dest.txt"); //2,選擇流 OutputStream os = null; try { os = new FileOutputStream(dest,true); //3,操作(寫出) String msg = "IO is so easy\r\n"; byte[] datas = msg.getBytes();//字串 --> 位元組陣列(編碼) os.write(datas, 0, datas.length); os.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ //4,釋放資源 if(null != os){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } } }