IO流
流是一組有順序的,有起點和終點的字節集合,是對數據傳輸的總稱或抽象。即數據在兩設備間的傳輸稱爲流,流的本質是數據傳輸,根據數據傳輸特性將流抽象爲各種類,方便更直觀的進行數據操作。
File
構造方法
File(String directoryPath, String filename)
File(File dirObj, String filename)
創建文件(夾)
boolean createNewFile();在指定路徑創建文件,如果文件已經存在,則不創建,返回false.輸出流對象一旦創建,如果文件存在,則會覆蓋boolean mkdirs():創建多級文件夾
刪除
void deleteOnExit():程序退出時刪除文件
判斷
isDirectory(); 是否是目錄
isHidden(); 是否隱藏
isAbsolute();
獲取信息
getPahth();//獲取路徑
getAbsoluteFile();//獲取絕對路徑封裝成文件對象
getAbsolutPath();//獲取絕對路徑
getParent(); 返回此抽象路徑名的父路徑名的抽象路徑名
lastModified();
length();
getParent();//該方法返回的是絕對路徑中的父目錄,如果獲取的是相對路徑,返回null.如果相對路徑中有一級目錄,那麼該目錄就是返回結果
renameto()
list() 這些字符串指定此抽象路徑名錶示的目錄中的文件和目錄。可以傳過來策略
listFiles() 列出文件路徑可以傳過來策略
常見操作:遞歸刪除
public static void deleteAll(File file){
if(file.isFile() || file.list().length == 0){
file.delete();
}
else{
File[] files = file.listFiles();
for(File f : files) {
deleteAll(f);
f.delete();
}
}
}
流
流的分類
2)從流結構上可分爲字節流(以字節爲處理單位或稱面向字節)和字符流(以字符爲處理單位或稱面向字符)。
字節流的輸入流和輸出流基礎是InputStream和OutputStream這兩個抽象類,字節流的輸入輸出操作由這兩個類的子類實現。
字符流是Java 1.1版後新增加的以字符爲單位進行輸入輸出處理的流,字符流輸入輸出的基礎是抽象類Reader和Writer
在最底層,所有的輸入/輸出都是字節形式的。基於字符的流只爲處理字符提供方便有效的方法。
3)按數據操作分節點流和過濾流
節點流:從特定的地方讀寫的流類,例如:磁盤或一塊內存區域。
過濾流:使用節點流作爲輸入或輸出。過濾流是使用一個已經存在的輸入流或輸出流連接創建的,是對節點流的加工。
輸出:節點流—>過濾流
輸入:節點流<—過濾流
字節流
輸入流:InputStream
2)層次
節點流(和源交互) | 過濾流 | ||
FileInputStream | |||
ObjectInputStream | LineNumberInputStream | ||
InputStream | FilterInputStream | ---------> | DataInputStream |
PipedInputStream | BufferedInputStream | ||
SequenceInputStream | PushbackInputStream | ||
StringBufferInputStream |
3)基本方法
abstractint read():讀取一個字節數據,並返回讀到的數據,如果返回-1,表示讀到了輸入流的末尾。
int read(byte[]b):將數據讀入一個字節數組,同時返回實際讀取的字節數。如果返回-1,表示讀到了輸入流的末尾。
int read(byte[] b, intoff, intlen) :將數據讀入一個字節數組,同時返回實際讀取的字節數。如果返回-1,表示讀到了輸入流的末尾。off指定在數組b中存放數據的起始偏移位置;len指定讀取的最大字節數。
void close():關閉輸入流,釋放和這個流相關的系統資源。
輸出流:OutputStream
1)OutputStream是定義了流式字節輸出模式的抽象類。2)層次
節點流(和源交互) | 過濾流 | ||
FileOutputStream | |||
ByteArrayOutputStream | PrintStream | ||
OutputStream | FilterOutputStream | ---------> | DataOutputStream |
ObjectOutputStream | BufferedOutputStream | ||
PipedOutputStream | PushbackInputStream | ||
3)基本方法
abstract void write(intb) :往輸出流中寫入一個字節。
void write(byte[]b) :往輸出流中寫入數組b中的所有字節。
void write(byte[]b, intoff, nt len) :往輸出流中寫入數組b中從偏移量off開始的len個字節的數據
void flush() :刷新輸出流,強制緩衝區中的輸出字節被寫出。
void close():關閉輸出流,釋放和這個流相關的系統資源(flush)。
字節流
FileInputStream 類創建一個能從文件讀取字節的InputStream 類,它的兩個常用的構造
方法如下
–FileInputStream(String filepath)
–FileInputStream(File fileObj)
例如:
InputStream is = new FileInputStream("c:/hello.txt");
byte[] buffer = new byte[200];
int length = 0;
while(-1 != (length = is.read(buffer, 0, 200))) {
String str = new String(buffer,0, length);
System.out.println(str);
}
is.close();
FileOutputStream 創建了一個可以向文件寫入字節的類OutputStream,它常用的構造方法如下FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
例如:
OutputStream os = new FileOutputStream("c:\\out.txt", true);
String str = "aaaaa";
byte[] buffer = str.getBytes();
os.write(buffer);
os.close();
2)BufferedInputStream和BufferedOutputStream過濾流,需要使用已經存在的節點流來構造,提供帶緩衝的讀寫,提高了讀寫的效率,減少頻繁訪問物理硬件,效率低。OutputStream os = new FileOutputStream("1.txt");
BufferedOutputStream bos = new BufferedOutputStream(os);
bos.write("http://www.google.com".getBytes());
bos.close();
os.close();
3)ByteArrayInputStream與ByteArrayOutputStreamByteArrayInputStream是把字節數組當成的輸入流。該類有兩個構造方法,每個造方法需要一個字節數組提供數據源
–ByteArrayInputStream(byte array[ ])
–ByteArrayInputStream(byte array[ ], intstartnumBytes)
String temp = "abc";
byte[] b = temp.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(b);
for(int i = 0; i < 2; i++){
int c;
while(-1 != (c = in.read())){
if(0 == i) {
System.out.println((char)c);
}else{
System.out.println(Character.toUpperCase((char)c));
}
}
System.out.println();
in.reset();
}
ByteArrayOutputStream是一個把字節數組當作輸出流的實現。ByteArrayOutputStream有兩個構造方法–ByteArrayOutputStream( )
–ByteArrayOutputStream(intnumBytes)
–在第一種形式裏,一個32位字節的緩衝區被生成。第二個構造方法生成一個numBytes大小的緩衝區。緩衝區保存在ByteArrayOutputStream的受保護的buf成員裏。緩衝區的大小在需要的情況下會自動增加。緩衝區保存的字節數是由ByteArrayOutputStream的受保護的count域保存的
ByteArrayOutputStream f = new ByteArrayOutputStream();
String str = "hello world welcome";
byte[] buffer = str.getBytes();
f.write(buffer);
byte[] result = f.toByteArray();
for(int i = 0; i < result.length; i++){
System.out.println((char)result[i]);
}
OutputStream os = new FileOutputStream("test.txt");
f.writeTo(os);
f.close();
os.close();
使用數據文件流的一般步驟
–(1)建立字節文件流對象;
–(2)基於字節文件流對象建立數據文件流對象;
–(3)用流對象的方法對基本類型的數據進行輸
入/輸出。
如:
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data.txt")));
byte b = 3;
int i = 12;
char ch = 'a';
float f = 3.3f;
dos.writeByte(b);
dos.writeInt(i);
dos.writeChar(ch);
dos.writeFloat(f);
dos.close();
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("data.txt")));
//讀和寫的順序要保持一致
System.out.println(dis.readByte());
System.out.println(dis.readInt());
System.out.println(dis.readChar());
System.out.println(dis.readFloat());
4)PipedInputStream和PipedOutputStream管道流,用於線程間的通信。一個線程的PipedInputStream對象從另一個線程的PipedOutputStream對象讀取輸入。要使管道流有用,必須同時構造管道輸入流和管道輸出流。
過濾流
2)類FilterInputStream和FilterOutputStream分別作爲所有過濾輸入流和輸出流的父類。
3)過濾流可以包裝節點流,過濾流可在包裝過濾流,進行功能豐富。
如:DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data.txt")));
輸出二進制形式緩衝方式輸出文件
字符流
既然Java的一個主要目的是支持“只寫一次,到處運行”的哲學,包括直接的字符輸入/輸出支持是必要的。
由於Java採用16位的Unicode字符,因此需要基於字符的輸入/輸出操作。從Java1.1版開始,加入了專門處理字符流的抽象類Reader和Writer,前者用於處理輸入,後者用於處理輸出。這兩個類類似於InputStream和OuputStream,也只是提供一些用於字符流的規定,本身不能用來生成對象。
Reader和Writer類也有較多的子類,與字節流類似,它們用來創建具體的字符流對象進行I/O操作。字符流的讀寫等方法與字節流的相應方法都很類似,但讀寫對象使用的是字符。
字符流:Reader
1) Reader中包含一套字符輸入流需要的方法,可以完成最基本的從輸入流讀入數據的功能。2) 層次
BufferedReader | ----------- | LineNumberReader | |
CharArrayReader | |||
Reader | FilterReader | ----------- | PushbackReader |
InputStreamReader | ----------- | FileReader | |
PipedReader | |||
StringReader |
字符流:Writer
1) Writer中包含一套字符輸出流需要的方法,可以完成最基本的輸出數據到輸出流的功能。2) 層次
BufferedWriter | |||
CharArrayWriter | |||
FilterWriter | |||
Writer | OutputStreamWriter | ----------- | FileWriter |
PipedWriter | |||
PrintWriter | |||
StringWriter |
InputStreamReader和OutputStreamWriter
主要構造:
public InputSteamReader(InputSteam in) 字節變字符
public InputSteamReader(InputSteam in,String enc)
public OutputStreamWriter(OutputStream out) 字符變字節
public OutputStreamWriter(OutputStream out,String enc)
其中in和out分別爲輸入和輸出字節流對象,enc爲指定的編碼規範(若無此參數,表示使用當前平臺的缺省規範,可用getEncoding()方法得到當前字符流所用的編碼方式)。
• 讀寫字符的方法read()、write(),關閉流的方法close()等與Reader和Writer類的
同名方法用法都是類似的。
public static void main(String[] args) throws Exception{
FileOutputStream fos = new FileOutputStream("file.txt"); //字節流
OutputStreamWriter osw = new OutputStreamWriter(fos); //字符流,橋樑
BufferedWriter bw = new BufferedWriter(osw);//過濾封裝
bw.write("http://www.google.com");
bw.write("\n");
bw.write("http://www.baidu.com");
bw.close();
FileInputStream fis = new FileInputStream("file.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
while(null != str){
System.out.println(str);
str = br.readLine();
}
br.close();
}
常見字符流操作
BufferedReader 通過緩衝輸入提高性能。它有兩個構造方法
–BufferedReader(Reader inputStream)
–BufferedReader(Reader inputStream, int bufSize)
–第一種形式創建一個默認緩衝區長度的緩衝字符流。第二種形式,緩衝區長度由bufSize傳入
例子:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String str;
while(null != (str = br.readLine())) {
System.out.println(str);
}
br.close();
BufferedWriter是一個增加了flush( )方法的Writer。flush( )方法可以用來確保數據緩衝區確實被寫到實際的輸出流。用BufferedWriter 可以通過減小數據被實際的寫到輸出流的次數而提高程序的性能。
BufferedWriter有兩個構造方法:
–BufferedWriter(Writer outputStream)
–BufferedWriter(Writer outputStream, int bufSize)
–第一種形式創建了使用默認大小緩衝區的緩衝流。第二種形式中,緩衝區大小是由bufSize參數傳入的
例子如上上
2)FileReader與FileWriter
FileReader類創建了一個可以讀取文件內容的Reader類。FileReader繼承於InputStreamReader。它最常用的構造方法顯示如下
–FileReader(String filePath)
–FileReader(File fileObj)
例如:
FileReader fr = new FileReader("c:\\FileReader1.java");
BufferedReader br = new BufferedReader(fr);
String str;
while (null != (str = br.readLine())) {
System.out.println(str);
}
br.close();
FileWriter 創建一個可以寫文件的Writer 類。 FileWriter繼承於OutputStreamWriter.它最常用的構造方法如下: –FileWriter(String filePath)
–FileWriter(String filePath, boolean
append)
–FileWriter(File fileObj)
–append :如果爲 true,則將字節寫入文件末尾處,而不是寫入文件開始處
例如:
String str = "hello world welcome nihao hehe";
char[] buffer = new char[str.length()];
str.getChars(0, str.length(), buffer, 0);
FileWriter f = new FileWriter("file2.txt");
for(int i = 0; i < buffer.length; i++) {
f.write(buffer[i]);
}
f.close();
3)CharArrayReader與CharArrayWriterCharArrayReader 是一個把字符數組作爲源的輸入流的實現。該類有兩個構造方法,每一個都需要一個字符數組提供數據源
–CharArrayReader(char array[ ])
–CharArrayReader(char array[ ], int start, int numChars)
例如:
String tmp = "abcdefg";
char[] ch = new char[tmp.length()];
tmp.getChars(0, tmp.length(), ch, 0);
CharArrayReader input = new CharArrayReader(ch);
int i;
while(-1 != (i = input.read())) {
System.out.println((char)i);
}
CharArrayWriter 實現了以數組作爲目標的輸出流。CharArrayWriter 有兩個構造方法 –CharArrayWriter( )
–CharArrayWriter(int numChars)
–第一種形式,創建了一個默認長度的緩衝區。
–第二種形式,緩衝區長度由numChars指定。緩衝區保存在CharArrayWriter的buf 成員中。緩衝區大小在需要的情況下可以自動增長。