在從File類開始IO系統介紹一文中,我們具體的介紹了File類。這個類非常有用,我們可以用它作橋梁把文件和流輕松的聯系起來。在java IO專題中,我預備先介紹一些實用的關于Java IO編程方法,而不是先從整體來把握IO,因為我覺得那樣效果并不好。當我們解決了這些平時開發中涉及到的問題后,再總結一下Java的IO系統。
當我們要對文件進行操作的時候,我們首先要確定我們對什么樣的文件進行操作,是二進制的文件例如圖片還是字符類型的文本文件,這非常的重要。當我們對二進制的文件處理的時候,我們應該使用FileInputStream和FileOutputStream,對文本文件的處理將在后面的文章講述。
當我們操作文件的時候,可以首先使用File類得到對這個文件的引用,例如
File file = new File("Idea.jpg");然后把file作為參數傳給FileInputStream或者FileOutputStream得到相應的輸入流或者輸出流。通常我們對文件無非是進行讀寫,修改,刪除等操作。最重要的就是讀寫操作。當我們讀文件的時候應該使用InputStream,寫文件的時候使用OutputStream。read()方法是在InputStream中定義的,它是個抽象方法。InputStream當然也是個抽象類,我們得到的實例都是它的子類,例如FileInputStream,子類假如不是抽象類的話就要實現父類的抽象方法。在FileInputStream中不但實現了read()并且重載了這個方法提供了read(byte[] buffer)和read(byte[] buffer,int off,int length)兩個方法。下面具體介紹一下:
read()方法將讀取輸入流中的下一個字節,并把它作為返回值。返回值在0-255之間,假如返回為-1那么表示到了文件結尾。用read()我們可以一個一個字節的讀取并根據返回值進行判定處理。
while((ch = image.read())!=-1)
{
System.out.PRint(ch);
newFile.write(ch);
}
read(byte[] buffer)會把流中一定長度的字節讀入buffer中,返回值為實際讀入buffer的字節長度,假如返回-1表示已經到了流的末尾。
while((ch = image.read(buffer))!=-1)
{
System.out.println(ch);
newFile.write(buffer);
}
read(byte[] buffer,int off,int length)的意思是把流內length長度的字節寫入以off為偏移量的buffer內,例如off=7,length=100的情況下,這個方法會從流中讀100個字節放到buffer[7]到buffer[106]內。返回值為實際寫入buffer的字節長度。
while((ch = image.read(buffer,10,500))!=-1)
{
System.out.println(ch);
newFile.write(buffer,10,500);
}
對上面的方法進行介紹的時候我們沒有考慮異常的情況,讀者應該參考API doc進行必要的了解。當我們對流操作的時候,有的時候我們可以對流進行標記和重置的操作,當然要流支持這樣的操作。參考一下mark(),reset()和markSupported()方法的說明。最后在使用結束后,確保關閉流,調用close()方法。由于FileOutputStream的write相關的方法和FileInptutStream的read()非常類似,因此不再多說。下面提供一個例子說明如何對二進制文件進行操作,我們打開一個JPEG格式的文件,通過三種不同的方式讀取內容,并生成一個新的文件。運行結束后你會發現這兩個文件完全一樣!
import java.io.*;
public class LinkFile
{
public static void main(String[] args) throws IOException
{
linkBinaryFile("Idea.jpg");
}
private static void linkBinaryFile(String fileName) throws IOException
{
File imageFile = new File(fileName);
if(!imageFile.exists()&&!imageFile.canRead())
{
System.out.println("can not read the image or the image file doesn't exists");
System.exit(1);
}
long length = imageFile.length();
int ch = 0;
System.out.println(length);
byte[] buffer = new byte[(int)length/7];
InputStream image = new FileInputStream(imageFile);
File file = new File("hello.jpg");
if(!file.exists())
{
file.createNewFile();
}
FileOutputStream newFile = new FileOutputStream(file,true);
boolean go = true;
while(go)
{
System.out.println("please select how to read the file:/n"+
"1: read()/n2:read(byte[] buffer)/n3:read(byte[] buffer,int off,int len)/n");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
if(line.equals("1"))
{
while((ch = image.read())!=-1)
{
System.out.print(ch);
newFile.write(ch);
}
}
else if(line.equals("2"))
{
while((ch = image.read(buffer))!=-1)
{
System.out.println(ch);
newFile.write(buffer);
}
}
else if(line.equals("3"))
{
while((ch = image.read(buffer,10,500))!=-1)
{
System.out.println(ch);
newFile.write(buffer,10,500);
新聞熱點
疑難解答