黑馬程序員-java基礎-IO流

-------------------------ASP.Net+Unity開發、.Net培訓、期待與您交流!--------------------------

IO流

1、IO流的分類
按操作數據分爲:字節流和字符流
按流的流向分爲:輸入流和輸出流
2、IO流的作用
IO流是用來處理設備之間的數據傳輸的。java對數據的操作是通過流的方式。
3、IO 流的抽象基類
第一,字節流的抽象基類:InputStream和OutputStream
第二,字符流的抽象基類:Reader和Writer

-----------------------------------------------------------------------------
字符流
1
、字符流一般是操作純文本文件的,一般用流FileReader和FileWriter
後綴名是父類名。 前綴名是該流對象的功能。
讀取文件用FileReader,而寫入文件則用流FileWriter
2、FileWriter流,即向文件中寫入數據的流
例子:需求:在硬盤上,創建一個文件並寫入一些文字數據。

找到一個專門用於操作文件的Writer子類對象。FileWriter

例子:

import java.io.*;
		class  FileWriterDemo
		{
			public static void main(String[] args) throws IOException
			{
				//創建一個FileWriter對象。該對象一被初始化就必須要明確被操作的文件。
				//而且該文件會被創建到指定目錄下。如果該目錄下已有同名文件,將被覆蓋。
				//其實該步就是在明確數據要存放的目的地。
				FileWriter fw = new FileWriter("demo.txt");
				//調用write方法,將字符串寫入到流中。
				fw.write("abcde");
				//刷新流對象中的緩衝中的數據。
				//將數據刷到目的地中。
				//fw.flush();

				//關閉流資源,但是關閉之前會刷新一次內部的緩衝中的數據。
				//將數據刷到目的地中。
				//和flush區別:flush刷新後,流可以繼續使用,close刷新後,會將流關閉。
				fw.close();
			}
		}
		若想對上面的文件接着繼續寫,則寫成
		         FileWriter fw = new FileWriter("demo.txt",true);
				fw.write("fghio");
				fw.close();
3、FileReader即對已經存在的文件進行讀取,讀取有兩種方式
第一種方式:用read()即一次讀取一個字符,並返回int型,即字符相對應的ASCII碼值
代碼:

import java.io.*;
			class  FileReaderDemo
			{
				public static void main(String[] args) throws IOException
				{
					//創建一個文件讀取流對象,和指定名稱的文件相關聯。
					//要保證該文件是已經存在的,如果不存在,會發生異常FileNotFoundException
					FileReader fr = new FileReader("demo.txt");

					//調用讀取流對象的read方法。
					//read():一次讀一個字符。而且會自動往下讀。
					int ch = 0;
					while((ch=fr.read())!=-1)
					{
						System.out.println(
					}
					fr.close();
				}
			}
			第二種方式:利用方法 int read(char[] cbuf):將字符讀入數組
						返回的值是讀取的字符數。
			import java.io.*;
			class FileReaderDemo2 
			{
				public static void main(String[] args) throws IOException
				{
					FileReader fr = new FileReader("demo.txt");
					//定義一個字符數組。用於存儲讀到字符。
					//該read(char[])返回的是讀到字符個數。
					char[] buf = new char[1024];
					int num = 0;
					while((num=fr.read(buf))!=-1)
					{
						System.out.println(new String(buf,0,num));
					}
					fr.close();
				}
			}
4、字符流的綜合練習
需求:將c盤中的一個文本文件複製到D盤

/*
複製的原理:
其實就是將C盤下的文件數據存儲到D盤的一個文件中。

步驟:
1,在D盤創建一個文件。用於存儲C盤文件中的數據。
2,定義讀取流和C盤文件關聯。
3,通過不斷的讀寫完成數據存儲。
4,關閉資源。
*/
import java.io.*;
class CopyText 
{
	public static void main(String[] args) throws IOException
	{
		copy_2();
	}
	//第二種讀取文件的方式:即將數據先讀入到數組中的方式。
	public static void copy_2()
	{
		FileWriter fw = null;
		FileReader fr = null;
		try//對異常進行處理
		{
			fw = new FileWriter("SystemDemo_copy.txt");
			fr = new FileReader("SystemDemo.java");
			//定義一個數組來存放讀取到的數據
			char[] buf = new char[1024];
			
			int len = 0;
			while((len=fr.read(buf))!=-1)
			{
				//將數組中的有效數據寫入流中
				fw.write(buf,0,len);
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException("讀寫失敗");
		}
		finally//此代碼塊中,存放是關閉資源的操作,由於是必須關閉資源,所以放在finally代碼塊中
		{
			if(fr!=null)
				try
				{
					fr.close();
				}
				catch (IOException e)
				{
				}
			if(fw!=null)
				try
				{
					fw.close();
				}
				catch (IOException e)
				{
				}
		}
	}
	//從C盤讀一個字符,就往D盤寫一個字符。
	public static void copy_1()throws IOException
	{
		//創建目的地。
		FileWriter fw = new FileWriter("RuntimeDemo_copy.txt");
		//與已有文件關聯。
		FileReader fr = new FileReader("RuntimeDemo.java");
		int ch = 0;
		while((ch=fr.read())!=-1)
		{
			fw.write(ch);
		}
		fw.close();
		fr.close();
	}
}
--------------------------------------------------------------------------
字節流
1
、字節流是用於操作圖片的,即用操作媒體信息的。
2、字節流的讀寫流是:FileInputStream和FileOutputStrean
FileInputStream是對文件進行讀取操作;
FileOutStream是對將信息向文件中寫入。
3、FileInputStream
讀取文件的方式有三種:第一,利用字節流的特有方法:int available()返回文件中的字節數
第二,用int read()即一次讀取一個字節的方式
第三,用int read(數組)即將讀取到的字節存入到數組中。
例子:需求,讀取一個文件數據,並打印在控制檯上
代碼:

import java.io.*;
		class  FileStream
		{
			public static void main(String[] args) throws IOException
			{
				readFile_3();
			}
			//利用字節流的特有方法進行讀取。只是用此方法時文件不能太大,否則內存會溢出。
			public static void readFile_3()throws IOException
			{
				FileInputStream fis = new FileInputStream("fos.txt");
				//int num = fis.available();
				byte[] buf = new byte[fis.available()];//定義一個剛剛好的緩衝區。不用在循環了。
				//將信息讀入數組中
				fis.read(buf);
				System.out.println(new String(buf));
				fis.close();
			}
			//利用方法int read(數組)來讀取信息
			public static void readFile_2()throws IOException
			{
				FileInputStream fis = new FileInputStream("fos.txt");
				byte[] buf = new byte[1024];
				int len = 0;
				while((len=fis.read(buf))!=-1)
				{
					System.out.println(new String(buf,0,len));
				}
				fis.close();	
			}
			//利用一次讀取一個字符的方法來讀取,即int read()
			public static void readFile_1()throws IOException
			{
				FileInputStream fis = new FileInputStream("fos.txt");

				int ch = 0;

				while((ch=fis.read())!=-1)
				{
					System.out.println((char)ch);
				}
				fis.close();
			}
		}
4、字節流的綜合運用

/*
複製一個圖片
思路:
1,用字節讀取流對象和圖片關聯。
2,用字節寫入流對象創建一個圖片文件。用於存儲獲取到的圖片數據。
3,通過循環讀寫,完成數據的存儲。
4,關閉資源。
*/
import java.io.*;
class  CopyPic
{
	public static void main(String[] args) 
	{
		FileOutputStream fos = null;
		FileInputStream fis = null;
		try
		{
			//定義輸出流與文件相關聯
			fos = new FileOutputStream("c:\\2.bmp");
			//定義輸入流與要讀取的文件相關聯
			fis = new FileInputStream("c:\\1.bmp");
			//定義一個數組,將信息讀入數組中
			byte[] buf = new byte[1024];
			int len = 0;
			//通過for循環來將文件中的信息讀取完
			while((len=fis.read(buf))!=-1)
			{
				fos.write(buf,0,len);
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException("複製文件失敗");
		}
		finally//關閉資源
		{
			try
			{
				if(fis!=null)
					fis.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException("讀取關閉失敗");
			}
			try
			{
				if(fos!=null)
					fos.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException("寫入關閉失敗");
			}
		}
	}
}
--------------------------------------------------------------------------
字符流的緩衝區
1
、字符流的緩衝區,,內部封裝的是數組
讀取緩衝區BufferedReader,提供了方法:String readLine(),即一次讀取一行
返回的是讀取到的改行的字符串,不包含任何行終止符。如果已經達到末尾
則返回null
寫入緩衝區BufferedWriter,提供了方法,newLine()即換行
2、緩衝區的綜合運用
需求:通過緩衝區複製一個.java文件。

import java.io.*;
class  CopyTextByBuf
{
	public static void main(String[] args) 
	{
		//定義兩個流緩衝區:讀取流緩衝區和寫入流緩衝區
		BufferedReader bufr = null;
		BufferedWriter bufw = null;
		try
		{
			bufr = new BufferedReader(new FileReader("BufferedWriterDemo.java"));
			bufw = new BufferedWriter(new FileWriter("bufWriter_Copy.txt"));
			//通過循環利用方法readLine,一次讀取一行的操作來進行讀取信息
			String line = null;
			//readLine方法,底層調用的仍是read()方法
			while((line=bufr.readLine())!=null)
			{
				bufw.write(line);//將讀取到的信息寫入緩衝區流中
				bufw.newLine();//利用寫入流緩衝區的換行功能來換行,因爲line中並不包括換行符
				bufw.flush();//刷新緩衝區,記住,只要用到緩衝區就要記得刷新。
			}
		}
		catch (IOException e)
		{
			throw new RuntimeException("讀寫失敗");
		}
		finally//關閉系統資源
		{
			try
			{
				if(bufr!=null)
					bufr.close();//由於關閉緩衝區,就是關閉緩衝區中的流對象,
								//最終關閉的是系統資源,所以此處就不用再寫關閉流對象了。
			}
			catch (IOException e)
			{
				throw new RuntimeException("讀取關閉失敗");
			}
			try
			{
				if(bufw!=null)
					bufw.close();
			}
			catch (IOException e)
			{
				throw new RuntimeException("寫入關閉失敗");
			}
		}
	}
}
--------------------------------------------------------------------------
字節流緩衝區
包括BufferedInputStream和BufferedOutputStream,底層封裝的是數組,所以讀取時,
不用再用read(數組)來讀取了
注意:
第一,BufferedInputStream並沒有功能readLine(),
readLine()功能是字符流緩衝區特有的
第二,BufferedOutputStream並沒有功能newLine()
newLine()功能是字符流讀出流緩衝區特有的。
對字節流緩衝區的綜合運用

/*
演示mp3的複製。通過緩衝區。
BufferedOutputStream
BufferedInputStream
*/
import java.io.*;
class  CopyMp3
{
	public static void main(String[] args) throws IOException
	{
		long start = System.currentTimeMillis();
		copy();
		long end = System.currentTimeMillis();

		System.out.println((end-start)+"毫秒");
	}

	//通過字節流的緩衝區完成複製。
	public static void copy()throws IOException
	{
		BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("c:\\0.mp3"));
		BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("c:\\1.mp3"));
		int by = 0;
		while((by=bufis.read())!=-1)
		{
			bufos.write(by);
		}
		bufos.close();
		bufis.close();	
	}
}
-------------------------------------------------------------------------------------------
字節流和字符流之間的轉換流
1
、讀取流轉換流:InputStreamReader,是字節流通向字符流的橋樑
2、寫入流轉換流:OutputStreamReader:是字符流通向字節流的橋樑
3、InputStream System.in:對應的標準輸入設備:鍵盤,返回值爲InputStream
PrintStream System.out:對應的標準輸出設備:控制檯,返回值爲PrintStream,即是OutputStream的子類。
4、鍵盤錄入的最常見寫法爲:BufferedReader bufr =
new BufferedReader(new InputStreamReader(System.in));
輸出設備的最常見的寫法
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));
綜合運用

需求:
		通過鍵盤錄入數據。
		當錄入一行數據後,就將該行數據進行打印。
		如果錄入的數據是over,那麼停止錄入。
		*/
		import java.io.*;
class  TransStreamDemo
{
	public static void main(String[] args) throws IOException
	{
		/*獲取鍵盤錄入對象。
		InputStream in = System.in;

		//將字節流對象轉成字符流對象,使用轉換流。InputStreamReader
		InputStreamReader isr = new InputStreamReader(in);

		//爲了提高效率,將字符串進行緩衝區技術高效操作。使用BufferedReader

		BufferedReader bufr = new BufferedReader(isr);
		*/
			
		//將上面簡化爲如下,也是鍵盤的最常見寫法。
		BufferedReader bufr = 
				new BufferedReader(new InputStreamReader(System.in));
		/*輸處設備流的轉換
		OutputStream out = System.out;
	  OutputStreamWriter osw = new OutputStreamWriter(out);
			BufferedWriter bufw = new BufferedWriter(osw);*/
			
		//輸出設備的最常見的寫法
		BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out));
		String line = null;
		while((line=bufr.readLine())!=null)
		{
			if("over".equals(line))
				break;
			bufw.write(line.toUpperCase());
			bufw.newLine();
			bufw.flush();
		}
		bufr.close();
	}
}
5、轉換流一般伴有字符編碼
常用到的編碼表示UTF-8和GBK,一般咱們所使用的文件的編碼表是GBK
UTF-8是三個字節代表一個字符,而GBK是兩個字節代表一個字符
例子:

import java.io.*;
class EncodeStream 
{
	public static void main(String[] args) throws IOException 
	{
			//writeText();
			readText();
	}
	//對文件以指定的編碼表進行讀取
	public static void readText()throws IOException 
	{
		//在流中執行了以彪編碼表GBK來讀取文件中的信息
		InputStreamReader isr = new InputStreamReader(new FileInputStream("utf.txt"),"gbk");
		//將文件讀入數組中
		char[] buf = new char[10];
		int len = isr.read(buf);
		//將數組轉換爲字符串
		String str = new String(buf,0,len);
		System.out.println(str);
		isr.close();//關閉資源
	}
	//以指定的編碼表形式向文件中寫入信息。
	public static void writeText()throws IOException 
	{
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("utf.txt"),"UTF-8");
		osw.write("你好");
		osw.close();
	}
}


 

-------------------------ASP.Net+Unity開發、.Net培訓、期待與您交流!--------------------------


詳情請查看:http://edu.csdn.net








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章