Java IO流之文件輸入輸出流
一.FileOutputStream(文件輸出流)
OutputStream是一個抽象類,抽象類必須通過子類實現。現在要向文件里輸出就要用FileOutputStream。
FileOutputStream有四個構造方法,分別為
1.FileOutputStream(File file)-------------向File對象的文件寫入數據
2.FileOutputStream(File file,boolean append);------向File對象的文件追加寫入數據
3.FileOutputStream(String path)-------------向指定文件寫入數據
4.FileOutputStream(String path,boolean append);--------向指定文件追加寫入數據
Advertisements
當append的值為true時,向文件中寫入的數據會追加到原數據的後面,否則會重寫該文件的數據。默認為false。
寫入方法1:一個個位元組寫入
Java代碼
public static void main(String[] args) {
try {
//創建一個文件位元組輸出流對象
OutputStream os=new FileOutputStream("L:\\io.txt");
//寫入的數據
String string="hello IO Stream";
byte[]bytes=string.getBytes();//轉化為位元組數組
for(int i=0;i<bytes.length;i++){
Advertisements
//向文件輸出
os.write(bytes[i]);
}
os.close();//關閉流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
方法二:全部一次寫入
Java代碼
public static void main(String[] args) {
try {
//創建一個文件位元組輸出流對象
OutputStream os=new FileOutputStream("L:\\io.txt",true);//追加
//寫入的數據
String string="hello IO Stream";
byte[]bytes=string.getBytes();//轉化為位元組數組
os.write(bytes);//全部寫入
//os.write(bytes,0,5)表示從0開始,寫入長度為5個位元組
os.close();//關閉流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
一.FileInputStream(文件輸入流)
FileInputStream是從系統的某個文件中獲得輸入位元組,有兩個構造方法
1.FileInputStream(File file)
2.FileInputStream(String path)
讀取位元組方法1:一個個位元組讀取
Java代碼
public static void main(String[] args) {
try {
//創建一個位元組輸入流對象
InputStream is=new FileInputStream("L:\\io.txt");
int b=-1;
while((b=is.read())!=-1)//位元組讀取,當為-1時讀取完畢
{
System.out.print((char)b);//轉化為字元輸出
}
is.close();//關閉流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
輸出結果為:hello IO Stream。這樣一個一個位元組讀取,速度很慢。
讀取位元組方法2:一次性讀取全部位元組
Java代碼
public static void main(String[] args) {
try {
File file=new File("L:\\io.txt");
//創建一個位元組輸入流對象
InputStream is=new FileInputStream(file);
//根據文件大小來創建位元組數組
byte[]bytes=new byte[(int)file.length()] ;
int len=is.read(bytes);//返回讀取位元組的長度
System.out.println("讀取位元組長度為:"+len);
System.out.println("讀取的內容為: "+new String(bytes));//構建成字元串輸出
is.close();//關閉流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
運行結果:
這種讀取方法主要缺點是要構建一個和文件大小一樣大的位元組數組,文件小的時候還可以,當文件很大,內存可能無法構架出如此大的位元組數組。所以,這種方法只適合小文件。
讀取位元組方法3:每次讀取指定長度(最常用的方法)
Java代碼
public static void main(String[] args) {
try {
//創建一個位元組輸入流對象
InputStream is=new FileInputStream("L:\\io.txt");
//指定每次讀取的大小--可根據性能位元組修改
byte[]bytes=new byte[8] ;
StringBuffer sb=new StringBuffer();
int len=-1;//每次讀取的實際長度
while((len=is.read(bytes))!=-1)
{
sb.append(new String(bytes,0,len));
}
System.out.println("讀取位元組為:"+sb);
is.close();//關閉流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
輸出結果:
---更多Java學習資料可關注微信公眾號:kaigexuetang_com(長按可複製關注)