JAVA-IO(1)操作簡介
阿新 • • 發佈:2019-02-14
Java IO操作主要指的是使用Java進行輸入輸出操作,Java的所有操作類都早Java.io包中,在使用時需要匯入此包.
在整個Java.io包中,最重要的是5個類和一個介面,5個類指的是:
File,OutputStream,InputStream,Writer,Reader
一個介面指的是:
Serializable.
============================================
一. File類操作簡介
在整個io包中,File是唯一一個與檔案本身有關的類.
新建檔案
String path = "C:" + File .separator + "test";
File f = new File(path);
f.createNewFile();
刪除檔案
String path = "C:" + File.separator + "test";
File f = new File(path);
f.delete();
建立資料夾
String path = "C:" + File.separator + "test";
File f = new File(path);
f.mkdir();
列出指定資料夾的全部檔案
public String[] list();//列出所有的名稱
public File[] listFiles();//列出完整的路徑
String path = "C:" + File.separator + "test";
File f = new File(path);
String[] paths = f.list();
for(int i=0;i<paths.length;i++){
System.out.println(paths[i]);
}
String path = "C:" + File.separator +"test";
File f = new File(path);
File[] files = f.listFiles();
for(int i=0;i<paths.length;i++){
System.out.println(files[i]);
}
判斷給定的路徑是否是目錄
String path = "C:" + File.separator +"test";
File f = new File(path);
f.isDirectory();//判斷
二. 位元組流OutputStream與InputStream
在Java中io操作也是有步驟的,以檔案的操作為例:
(1)使用File類開啟一個檔案;
(2)通過位元組流或字元流的子類置頂輸出的位置;
(3)進行讀寫操作;
(4)關閉輸入輸出;
1.位元組輸出流OutputStream
向檔案中寫入資料
//檔案不存在則會自動建立
File f = new File("C:" + File.separator + "test");
//寫入資料
FileOutputStream out = new FileOutputStream(f);
String str = "Hello World!";
byte[] b = str.getBytes();
out.write(b);
out.close();
追加新內容
File f = new File("C:" + File.separator + "test");
//引數true表示追加資料
FileOutputStream out2 = new FileOutputStream(f, true);
String str = "\r\nMy Girl!";
byte[] b = str.getBytes();
out.write(b);
out.close();
2.位元組輸入流InputStream
讀取資料
File f = new File("C:" + File.separator + "test");
//讀取資料
FileInputStream in = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
in.read(b);
in.close();
System.out.println(new String(b));
三. 字元流Writer與Reader
- 字元輸出流Writer
使用字元流寫入資料
//使用字元流寫入資料
File f = new File("C:" + File.separator + "test");
FileWriter writer = new FileWriter(f);
String str = "HELLO!";
writer.write(str);
writer.flush();
writer.close();
使用字元流追加內容
File f = new File("C:" + File.separator + "test");
FileWriter writer = new FileWriter(f,true);
String str = "\r\nWORLD!";
writer.write(str);
writer.flush();
writer.close();
- 字元輸入流Reader
使用字元流讀取資料
//使用字元流讀取資料
File f = new File("C:" + File.separator + "test");
FileReader reader = new FileReader(f);
char[] c = new char[(int) f.length()];
int len = reader.read(c);
reader.close();
System.out.println(new String(c,0,len));
&&& 字元流與位元組流的區別:
對於位元組流,直接操作檔案資料的讀寫
而對於字元流,則是通過緩衝區操作資料的讀寫
驗證:
不關閉資料流,位元組流可以寫成功
而字元流則不行.使用flush()方法就可以實現了
那麼,使用位元組流還是字元流好呢?
所有的檔案包括圖片在硬碟或在傳輸時,都是以位元組的形式進行,而字元只在記憶體中出現,所以位元組流使用較為廣泛.