Java 輸入、輸出流(I/O流)
- 1 File類
- 1.1 檔案的屬性
- 1.2 目錄
- 1.3 檔案的創建與洗掉
- 1.4 運行可執行檔案
- 2 檔案位元組輸入、輸出流
- 2.1 檔案位元組輸入流
- 2.2 檔案位元組輸出流
- 3 檔案字符輸入、輸出流
- 4 緩沖流
概述:輸入、輸出流提供一條通道程式,可以使用這條通道讀取源中的資料或把資料傳送到目的地,把輸入流的指向稱作源,程式從指向源的輸入流中讀取源中的資料;而輸出流的指向是資料要去的一個目的地,程式通過向輸出流中寫入資料把資料傳送到目的地,

1 File類
File物件主要用來獲取檔案本身的一些資訊,不涉及對檔案的讀寫操作
創建一個File物件的構造方法有3個,如下:
(1) File(String filename);//filename為檔案名
(2) File(String directoryPath,String filename);//directoryPath是檔案的路徑
(2) File(File dir,String filename);//dir為一個目錄
使用File(String filename);創建檔案時,該檔案位置默認為當前程式所在位置
1.1 檔案的屬性
File類的下列方法獲取檔案本身的一些資訊,
public String getName()//獲取檔案的名字,
public boolean canRead()//判斷檔案是否是可讀的,
public boolean canWrite()//判斷檔案是否可被寫入,
public boolean exits()//判斷檔案是否存在,
public long length()//獲取檔案的長度(單位是位元組),
public String getAbsolutePath()//獲取檔案的絕對路徑,
public String getParent()//獲取檔案的父目錄,
public boolean isFile()//判斷檔案是否是一個普通檔案,而不是目錄,
public boolean isDirectroy()//判斷檔案是否是一個目錄,
public boolean isHidden()//判斷檔案是否是隱藏檔案,
public long lastModified()//獲取檔案最后修改的時間,
例子1.1(例子中使用上述的一些方法,獲取某些檔案的資訊)
package Example1;
import java.io.File;
public class Example1_1 {
public static void main(String[] args) {
File file = new File("D:\\lifeilin", "lifeilin.txt");//創建檔案物件
try {
file.createNewFile();//創建一個新檔案
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("檔案是否存在:" + file.exists());
System.out.println(file.getName() + "是可讀的嗎:" + file.canRead());
System.out.println(file.getName() + "的長度:" + file.length());
System.out.println(file.getName() + "的絕對路徑:" + file.getAbsolutePath());
}
}

1.2 目錄
(1)創建目錄
public boolean mkdir()
(2)列出目錄中的檔案
public String[] list();用字串形式回傳目錄下的全部檔案,
public File [] listFiles();用File物件形式回傳目錄下的全部檔案,
public String[] list(FilenameFilter obj)用字串形式回傳目錄下的指定型別的所有檔案,
public File [] listFiles(FilenameFilter obj)用File物件形式回傳目錄下的指定型別所有檔案,
上述兩方法的引數FilenameFilter是一個介面,該介面有一個方法:
public boolean accept(File dir,String name);
例子2(Example1_2.java ,FileAccept.java ),例子2列出當前目錄(應用程式所在的目錄)下全部java檔案的名字)
FileAccept.java
package Example1_2;
import java.io.*;
public class FileAccept implements FilenameFilter {//FileAccept類實作FilenameFilter介面
private String extendName;
public void setExtendName(String s) {
extendName="."+s;
}
public boolean accept(File dir,String name) { //重寫介面中的方法
return name.endsWith(extendName);
}
}
Example1_2.java
package Example1_2;
import java.io.*;
public class Example1_2 {
public static void main(String[] args) {
File dirFile = new File(".");
FileAccept fileAccept = new FileAccept();
fileAccept.setExtendName("java");
String fileName[] = dirFile.list(fileAccept);
for (String name : fileName) {
System.out.println(name);
}
}
}
1.3 檔案的創建與洗掉
當使用File類創建一個檔案物件后,例如
File file=new File(“D:”,“letter.txt”);
如果D:\目錄中沒有名字為letter.txt檔案,檔案物件file呼叫方法
public boolean createNewFile();
檔案物件呼叫方法public boolean delete()可以洗掉當前檔案,
例如:
file.delete();
1.4 運行可執行檔案
?用Runtime類宣告一個物件( Runtime類在java.lang包)
Runtime ec;
?然后使用該類的getRuntime()靜態方法創建這個物件:
ec=Runtime.getRuntime();
ec可以呼叫 exec(String command) 方法打開本地機的可執行
檔案或執行一個操作,
下面例子演示打開本地的記事本:
import java.io.*;
public class Example1_4 {
public static void main(String[] args) {
try {
Runtime ce = Runtime.getRuntime();//創建物件
File file = new File("c:/windows", "Notepad.exe");
ce.exec(file.getAbsolutePath());//打開本地記事本
} catch (Exception e) {
System.out.println(e);
}
}
}
2 檔案位元組輸入、輸出流
?java.io包提供了大量的流類.
?Java把InputStream 抽象類的子類創建的流物件稱作位元組輸入流;OutputStream抽象類的子類創建的流物件稱作位元組輸出流,
?針對不同的源或目的地,java.io包為程式提供了相應的輸入流或輸出流,這些輸入、輸出流絕大部分都是InputStream、OutputStream、Reader或Writer的子類,
2.1 檔案位元組輸入流
使用輸入流通常包括4個基本步驟:
(1)設定輸入流的源
(2)創建指向源的輸入流
(3)讓輸入流讀取源中的資料
(4)關閉輸入流,
(1)構造方法:設定輸入流源
使用FileInputStream類的下列構造方法創建指向檔案的輸入流,
FileInputStream(String name);//使用給定的檔案名name創建FileInputStream流
FileInputStream(File file);//使用File物件創建FileInputStream流
//引數name和file指定的檔案稱為輸入流的源
FileInpuStream輸入流打開一個到達檔案的通道(源就是這個檔案,輸入流指向這個檔案),當創建輸入流時,可能會出現錯誤(也被稱為例外),例如,輸入流指向的檔案可能不存在,當出現I/O錯誤,Java 生成一個出錯信號,它使用IOException (IO例外)物件來表示這個出錯信號,程式必須在try-catch陳述句中的try塊部分創建輸入流,在catch (捕獲)塊部分檢測并處理這個例外,例如,為了讀取一個名為hello.txt 的檔案,建立一個檔案輸入流in,
try {
FileInputStream in = new FileInputStream("hello.txt");//創建指向檔案hello.txt的輸入流
} catch (IOException e) {
System.out.println("File read error:" + e);
}
或者:
File f = new File("hello.txt");//指定輸入流的源
try {
FileInputStream in = new FileInputStream(f);//創建指向源輸入流
} catch (IOException e) {
System.out.println("File read error:" + e);
}
(2)使用輸入流讀取位元組
檔案位元組流可以呼叫從父類繼承的read方法順序地讀取檔案,只要不關閉流,每次呼叫read方法就順序地讀取檔案中的其余內容,直到檔案的末尾或檔案位元組輸入流被關閉,
?int read();讀取單個位元組的資料,回傳位元組值(0~255整數) ,如果未讀出位元組就回傳-1,
?int read(byte b[]);讀取b.length個位元組到位元組陣列b中,回傳實際讀取的位元組數,如果到達檔案的末尾,則回傳-1,
?int read(byte b[], int off, int len);讀取len個位元組到位元組陣列b中,并回傳實際讀取的位元組數目,如果到達檔案的末尾,則回傳-1,引數off指定從位元組陣列的某個位置開始存放讀取的資料,
(3) 關閉流
輸入流都提供了關閉方法close(),盡管程式結束時會自動關閉所有的流,但是當程式使用完流后,顯示地關閉任何打開的流仍然是一個良好的習慣,如果沒有關閉那些被打開的流,那么就可能不允許另一個程式操作這些所用的資源,
下面例子使用檔案位元組流讀檔案內容:
import java.io.*;
public class Example2_1 {
public static void main(String[] args) {
int n = -1;
byte[] a = new byte[100];
try {
File f = new File("D:\\","Example2_1.java");
InputStream in = new FileInputStream(f);
while ((n = in.read(a, 0, 100)) != -1) {
String s = new String(a, 0, n);
System.out.print(s);
}
in.close();
} catch (IOException e) {
System.out.println("File read Error" + e);
}
}
}
2.2 檔案位元組輸出流
?使用輸出流通常包括4個基本步驟:
(1)給出輸出流的目的地
(2)創建指向目的地的輸出流
(3)讓輸出流把資料寫入到目的地
(4)關閉輸出流,
(1)構造方法
使用FileOutputStream類的下列具有重繪功能的構造方法創建指向檔案的輸出流,
FileOutputStream(String name);
FileOutputStream(File file);
//引數name和file指定的檔案稱為輸出流的目的地
FileOutpuStream輸出流開通一個到達檔案的通道(目的地就是這個檔案,輸出流指向這個檔案),需要特別注意的是,如果輸出流指向的檔案不存在,Java 就會創建該檔案,如果指向的檔案是已存在的檔案,輸出流將重繪該檔案(使得檔案的長度為0),另外,與創建輸入流相同,創建輸出流時,可能會出現錯誤(被稱為例外),例如,輸出流試圖要寫入的檔案可能不允許操作或有其他受限等原因,所以必須在try-catch陳述句中的try塊部分創建輸出流,在catch (捕獲)塊部分檢測并處理這個例外,例如,創建指向名為destin.txt的輸出流out,
try {
FileOutputStream out = new FileOutputStream("destin.txt");//創建指向檔案destin.txt的輸出流
} catch (IOException e) {
System.out.println("File writeerror:" + e);
}
或者:
File f = new File("destin.txt");//指定輸出流的源
try {
FileOutputStream out = new FileOutputStream (f);//創建指向源輸出流
} catch (IOException e) {
System.out.println("File write:" + e);
}
可以使用FileOutputStream類的下列能選擇是否具有重繪功能的構造方法創建指向檔案的輸出流,
FileOutputStream(String name, boolean append) ;
FileOutputStream(File file, boolean append) ;
當用構造方法創建指向一個檔案的輸出流時,如果引數append取值true, 輸出流不會重繪所指向的檔案(假如檔案已存在),輸出流的write的方法將從檔案的末尾開始向檔案寫入資料,引數append取值false, 輸出流將重繪所指向的檔案(假如檔案已存在),
(2)使用輸出流寫位元組
輸出流的wirie方法以位元組單位向目的地寫資料,
void write(int n)//向目的地寫入單個位元組,
void write(byte b[])//向目的地寫入一個位元組陣列,
void write(byte b[],int off,int len)//從位元組陣列中偏移量off處取len個位元組寫到目的地,
FileOutputStream流順序地寫檔案,只要不關閉流,每次呼叫write方法就順序地向目的地寫入內容,直到流被關閉,
(3)關閉流
通過呼叫close()方法,可以保證作業系統把流緩沖區的內容寫到它的目的地,即關閉輸出流可以把該流所用的緩沖區的內容沖洗掉(通常沖洗到磁盤檔案上),
例子2.2使用檔案位元組輸出流寫檔案a.txt,
例子2.2首先使用具有重繪功能的構造方法創建指向檔案a.txt的輸出流、并向a.txt檔案寫入“新年快樂”,然后再選擇使用不重繪檔案的構造方法指向a.txt,并向檔案寫入( 即尾加)“ Happy New Year
import java.io.*;
public class Example2_2 {
public static void main(String[] args) {
byte[] a = "新年快樂".getBytes();
byte[] b = "Happy New Year".getBytes();
File file = new File("D:\\","a.txt"); //輸出的目的地
try {
OutputStream out = new FileOutputStream(file); //指向目的地的輸出流
System.out.println(file.getName() + "的大小:" + file.length() + "位元組");//a.txt的大小:0位元組
out.write(a); //向目的地寫資料
out.close();
out = new FileOutputStream(file, true); //準備向檔案尾加內容
System.out.println(file.getName() + "的大小:" + file.length() + "位元組");///a.txt的大小:8位元組
out.write(b, 0, b.length);
System.out.println(file.getName() + "的大小:" + file.length() + "位元組");///a.txt的大小:8位元組
out.close();
} catch (IOException e) {
System.out.println("Error " + e);
}
}
}

3 檔案字符輸入、輸出流
?Java把Reader抽象類的子類創建的流物件稱作字符輸入流;Writer抽象類的子類創建的流物件稱作字符輸出流,
與FileInputStream. FileOutputStream位元組流相對應的是FileReader、FileWriter字符流(檔案字符輸入、輸出流),FileReader 和FileWriter 分別是Reader和Writer的子類,其構造方法分別是:
FileReader (String filename) ;
FileReader (File filename) ;
FileWriter (String filename) ;
FileWriter (File filename) ;
FileWriter (String filename, boolean append) ;
FileWriter (File filename,boolean append) ;
字符輸入流和輸出流的read和write方法使用字符陣列讀寫資料,即以字符為基本單位處理資料,
?1. Reader類提供的read方法以字符為單位順序地讀取源中的資料,
int read();
int read(char b[]);
int read(char b[], int off, int len);
void close();
?2. Writer流 以字符為單位順序地寫檔案,每次呼叫write方法就順序地向目的地寫入內容,Writer類有 如下常用的方法,
void write(int n)//向輸出流寫入一個字符,
void write(byte b[])//向輸出流寫入一個字符陣列,
void write(byte b[],int off,int length)//從給定字符陣列中起始于偏移量off處取len個字符寫到輸出流,
void close()//關閉輸出流,
例子3使用檔案字符輸入、輸出流將檔案a.txt的內容尾加到檔案b.txt中
import java.io.*;
public class Example3 {
public static void main(String args[]) {
File sourceFile = new File("a.txt"); //讀取的檔案
File targetFile = new File("b.txt"); //寫入的檔案
char c[] = new char[19]; //char型陣列
try {
Writer out = new FileWriter(targetFile, true); //指向目的地的輸出流
Reader in = new FileReader(sourceFile); //指向源的輸入流
int n = -1;
while ((n = in.read(c)) != -1) {
out.write(c, 0, n);
}
out.flush();
out.close();
} catch (IOException e) {
System.out.println("Error " + e);
}
}
}
注:對于Writer流,write 方法將資料首先寫入到緩沖區,每當緩沖區溢位時,緩沖區的內容被自動寫入到目的地,如果關閉流,緩沖區的內容會立刻被寫入到目的地,流呼叫flush0方法可以立刻沖洗當前緩沖區,即將當前緩沖區的內容寫入到目的地,
4 緩沖流
?BufferedReader和BufferedWriter類創建的物件稱作緩沖輸入、輸出流,二者的源和目的地必須是字符輸入流和字符輸出流,
?構造方法:
BufferedReader(Reader in);
BufferedWriter(Writer out);
BufferedReader流能夠讀取文本行,方法是readLine(),通過向BufferedReader 傳遞一個Reader子類的物件(如FileReader 的實體),來創建一個BufferedReader物件,如:
FileReader inOne = new FileReader ("Student. txt") ;
BufferedReader inTwo = BufferedReader (inOne) ;
然后inTwo流呼叫readLine()方法中讀取Student.txt,例如:
String strLine = inTwo. readLine () ;
類似地,可以將BufferedWriter流和FileWriter 流連接在一起, 然后使用BufferedWriter流將資料寫到目的地,例如:
FileWriter tofile = new FileWriter ("hello.txt") ;
BufferedWriter out = BufferedWriter (tofile) ;
然后out使用BufferedReader類的方法wite(tring s,int off,int len)把字串s寫到hello.txt中,引數off是s開始處的偏移量,len是寫入的字符數量,
另外,BufferedWriter 流有-一個獨特的向檔案寫入一 個回行符的方法
newLine() ;
?BufferedReader和BufferedWriter類讀 寫檔案的方法:
readLine()//讀取文本行
write(String s,int of,int len)//把字串s寫到檔案中
newLine();// 向檔案寫入一個回行符
由英陳述句子構成的檔案english. txt (每句占一行):
The arrow missed the target.
They rejected the union demand.
Where does this road go to?
例子4按行讀取english. txt,并在該行的后面尾加上該英陳述句子中含有的單詞數目,然后再將該行寫入到一個名字為englishCount. txt的檔案中
import java.io.*;
import java.util.*;
public class Example10_1 {
public static void main(String[] args) {
File fRead = new File("D:\\","english.txt");
File fWrite = new File("D:\\","englishCount.txt");
try {
Writer out = new FileWriter(fWrite);//指向目的地的輸出流
BufferedWriter bufferWrite = new BufferedWriter(out);
Reader in = new FileReader(fRead);//指向源的輸入流
BufferedReader bufferRead = new BufferedReader(in);
String str = null;
while ((str = bufferRead.readLine()) != null) {
StringTokenizer fenxi = new StringTokenizer(str);
int count = fenxi.countTokens();
str = str + " 句子中單詞個數:" + count;
bufferWrite.write(str);
bufferWrite.newLine();
}
bufferWrite.close();
out.close();
in = new FileReader(fWrite);
bufferRead = new BufferedReader(in);
String s = null;
System.out.println(fWrite.getName() + "內容:");
while ((s = bufferRead.readLine()) != null) {
System.out.println(s);
}
bufferRead.close();
in.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/277648.html
標籤:java
上一篇:SSM專案中使用攔截器和過濾器
