InputStream 和 OutStream 小練習,記錄一下
package InputOutput;
import java.io.*;
/**
* inputoutput 學習
* 文件的讀取,位置變化,從磁盤中讀到內厝,inputSream,
* 從內存中讀到磁盤,outputStream
* 字節流:inputStream outputSream
* 字符流:reader 、writer
*
*/
public class Stream {
public static void main(String[] args) throws IOException {
InputStream is = null;
OutputStream os= null ;
Long begin = System.currentTimeMillis();
try {
is = new FileInputStream("D:\\Study\\Wildlife.wmv");
File newFile = new File("D:\\Study\\Wildlife002.wmv");
os = new FileOutputStream(newFile);
// 如果操作的文件太大(單位M(兆)以上),花費時間太長,則需要增大緩衝區
byte [] buffer = new byte[1024];
//判斷文件是否存在
if(!newFile.exists()){
// 獲取到父類File對象,創建所有不存在的文件夾
newFile.getParentFile().mkdirs();
}
int length = 0 ;
while((length = is.read(buffer)) != -1){
os.write(buffer);
// 1、該方法會強制將緩衝區中的數據一次性寫出,不管緩衝區是否已經裝滿。
// 2、頻繁調用flush方法會提高寫出次數從而降低寫出效率,但是會保證寫出的及時性
os.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(is !=null){
is.close();
}
if(os != null){
//1、緩衝流會首先調用flush將剩餘在緩衝區中的數據先寫出
//2、然後再將緩衝流處理的流(高級流或者是低級流)關閉後,纔將自己關閉。
os.close();
}
}
Long end = System.currentTimeMillis();
System.out.println("times="+(end-begin));
}
}