最近學習了關於流的處理,及時的鞏固,滿滿的都是細節。
public static void main(String[] args){
// TODO Auto-generated method stub
//在關於流的處理代碼中,遇到異常最好不要直接拋出,雖然這樣並不會報錯,但是不利於後期代碼的維護,
//應該處理異常
FileInputStream in = null;//定義的時候最好是寫出“=null” 不要直接是FileInputStream in
FileOutputStream out = null;
FileOutputStream out1 = null;
try {
in = new FileInputStream("D:\\FileDemo\\demo\\b.txt");
out = new FileOutputStream("D:\\FileDemo\\demo\\demo1\\m.txt");
out1 = new FileOutputStream("D:\\FileDemo\\demo\\demo1\\n.txt");
//單字節讀取
int a;
while ((a = in.read()) != -1) { //返回:讀入緩衝區的字節總數,如果因爲已經到達文件末尾而沒有更多的數據,則返回 -1。
out.write(a); //一次讀取一個字節
}
//多字節讀取
int len;
byte [] b = new byte[512]; //一次讀取512個字節,中括號內的數字自定義但最好是2的次方
while((len=in.read(b))!=-1){
out1.write(b,0,len); //最好不要偷懶直接out1.write(b),這樣容易出問題
}
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
} finally {
try {
if (in != null) in.close(); //及時判斷關閉流,並且最好在finally語句塊中關閉
if (out != null) out.close();
if (out1 != null) out1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}