1. 程式人生 > >2018.3.12 流1

2018.3.12 流1

什麼是流?

流是一根帶有按鈕的管道, 流是用於資料傳輸的管道。

位元組流和字元流的區別: 位元組流可以傳輸文字或者音樂或者視訊等等的資料。 字元流只能傳輸文字檔案的資料。

位元組流讀檔案:

public class IO {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileInputStream fileReader = new FileInputStream("F:\\eclipsewoke\\2018_3_9\\src\\ShoppingTicket.java");

int a = 0;
a = fileReader.read();
while (a!=-1) {
System.out.print((char)a);
a = fileReader.read();
}
fileReader.close(); //關閉流
}

}

緩衝位元組流讀寫檔案:

public class CopFile {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedInputStream fileReader = new BufferedInputStream(new FileInputStream ("C:\\Users\\Administrator\\Desktop\\北京視屏\\junren.mp4")) ;

BufferedOutputStream fileWriter = new BufferedOutputStream(new FileOutputStream("F:/juju.mp4"));
byte[] buy =new byte[1024];
int len ;
len = fileReader.read(buy);
while(-1 != len){
fileWriter.write(buy,0,len);
len = fileReader.read(buy);
}
fileWriter.flush();
fileReader.close();
fileWriter.close();
}

}

帶緩衝字元流讀寫檔案:

//緩衝流BufferedReader BufferedWrite 字元流 
BufferedReader bufferedReader = new BufferedReader(new FileReader("F:\\aa.txt"));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("F:\\dd.txt"));
String str = null;
while(null!=(str= bufferedReader.readLine())){
bufferedWriter.write(str);
bufferedWriter.newLine();
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();