標籤:nbsp cat err info 接收 bcd 作用 span 輸出
一 讀取檔案
public static void main(String[] args) throws FileNotFoundException, IOException { // 建立File對象 File srcFile = new File(""); // 選擇流 InputStream isInputStream = null;// 提升範圍 try { isInputStream = new FileInputStream(srcFile); // 操作不斷讀取緩衝數組 byte[] car = new byte[10]; int len = 0;// 接收實際讀取大小 // 迴圈讀取 while (-1 != isInputStream.read(car)) { // 輸出位元組數組轉成字串 String info = new String(car, 0, len); System.err.println(info); } } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("檔案不存在"); } catch (IOException e) { e.printStackTrace(); System.out.println("讀取檔案失敗"); } finally { try { if (null != isInputStream) { isInputStream.close(); } } catch (Exception e) { e.printStackTrace(); System.out.println("關閉檔案輸入資料流失敗"); } } }
二寫出檔案
public static void main(String[] args) throws FileNotFoundException, IOException { // 建立File對象目的地 File dest = new File(""); // 選擇流,檔案輸出資料流OutputStream FileOutputStream OutputStream out = null;// 提升範圍 try { //true以追加的形式寫出檔案,否則是覆蓋 out = new FileOutputStream(dest,true); String str="abcdedg"; //字串轉位元組數組 byte[] data=str.getBytes(); out.write(data,0,data.length); out.flush();//強制重新整理出去 } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("檔案未找到"); } catch (IOException e) { e.printStackTrace(); System.out.println("寫出檔案失敗"); } finally { try { //釋放資源:關閉 if (null != out) { out.close(); } } catch (Exception e) { e.printStackTrace(); System.out.println("關閉檔案輸出資料流失敗"); } } }
java分享第七天-02(讀取檔案)