黑馬程序員_IO流2

  ------- android培訓java培訓、期待與您交流! ----------


一    File類、文件類

1 java將文件進行描述封裝,方便對文件進行操作

2 方法摘要:
createNewFile()  創建文件不存在,返回true。如果文件存在則不創建,返回false
mkdir()  創建一級文件目錄
mkdirs() 創建多級文件目錄
delete()  刪除文件
deleteOnExit()  退出時刪除
exists()  判斷文件是否存在
isFile()  判斷是否文件
isDirectory()  判斷是否目錄
isAbsolute()   判斷是否絕對路徑
getName() 獲取名稱
getPath()  獲取封裝路徑
getAbsolutePath()  獲取絕對路徑
getParent() 獲取父目錄
length () 獲取文件大小
renameTo()  改文件名
list()  獲取文件包含的文件及目錄,返回一個字符串數組
listFiles()  獲取文件包含的文件及目錄,返回一個文件數組

3 遞歸:定義一個函數,在函數調用自己。必須要有結束條件。

4 例子:

//例子:將一個目錄下的圖片文件的絕對路徑存到一個文件上
//需要用到遞歸,集合,IO流
import java.io.*;
import java.util.*;
class  Demo
{
	public static void main(String[] args) throws IOException
	{
		File file=new File("d:\\javacx");//創建一個文件對象
		List<File> list=new ArrayList<File>();//創建一個集合存儲文件
		fileToList(file,list);//調用功能將文件存到集合中
		String filename="a.txt";//定義一個文件名稱
		listToFile(list,filename);//將集合中的文件的絕對路徑通過流寫到文件中
		

	}
	//定義一個功能將集中的文件的絕對路徑存到一個文件中
	public static void listToFile(List<File> list,String filename) throws IOException
	{
		//定義字符寫入流
		BufferedWriter bufw=new BufferedWriter(new FileWriter(filename));
		//遍歷集合的文件
		for(File file:list)
		{
			//獲取文件的絕對路徑並寫到流中
			bufw.write(file.getAbsolutePath());
			bufw.newLine();//換行
			bufw.flush();//刷新
		}
		bufw.close();//關閉流資源
	}
	//定義一個功能將指定目錄中的.jpg文件存進集合
	public static void fileToList(File file,List<File> list)
	{
		//將目錄下的文件變成文件數組
		File[] files=file.listFiles();
		//遍歷文件數組
		for(File f: files)
		{
			//判斷文件是否是目錄,是的話就遞歸
			if (f.isDirectory())
			{
				fileToList(f,list);
			}
			//不是的話就把文件存進集合中
			else
			{
				//獲取文件名稱,並判斷名稱的後綴名
				String name=f.getName();
				if(name.endsWith(".jpg"))
					list.add(f);
			}
		}
	}
}


二    Properties

1 概述
(1)Properties是HashTable的子類,擁有HashTable的特性
(2)Properties是與IO流相結合的集合容器,用於鍵值對形式的配置文件,並且存儲的全是字符串

2 方法摘要:
setProperty(String key,String values)  添加元素,鍵值都是字符串
getProperty(String key)  通過鍵獲取值
stringPropertyNames()  獲取鍵集合
load(InputStream)  將流中的數據加載到集合
store(OutputStream,"")  將集合中的數據加載到流中

3 例子:定義一個限定運行次數的程序,次數一到,就給出提示並結束程序。

代碼:

/*思路:
1 創建集合
2 創建流
3 加載流中數據進集合
4 取出數據進行判斷,再自增
5 創建寫入流加載集合中的數據
*/
import java.io.*;
import java.util.*;
class  RunCountDemo
{
	public static void main(String[] args) throws IOException
	{
		//創建能與流關聯的集合
		Properties prop=new Properties();
		File file=new File("count.txt");
		//判斷文件是否存在,沒有的話就創建該文件
		if(!file.exists())
			file.createNewFile();
		//創建讀取流與文件相關聯
		FileReader fr=new FileReader(file);
		//加載流中的數據進集合
		prop.load(fr);
		int count=0;//定義一個計數器
		//獲取time所對應的值
		String values=prop.getProperty("time");
		if(values!=null)
		{
			//將值轉化爲基本數據類型進行判斷
			count=Integer.parseInt(values);
			if(count>=5)
			{
				//如果次數滿足條件,給出提示並結束程序
				System.out.println("用戶體驗次數已到,請註冊用戶");
				return;
			}
		}
		count++;//計數器自增
		prop.setProperty("time",count+"");//將新的鍵值對存進集合
		//定義一個寫入流並與文件相關聯
		FileWriter fw=new FileWriter(file);
		//將集合的數據存進與流相關聯的文件中
		prop.store(fw,"");
	}
}


三    打印流
1特點:可以將各種數據類型的數據原樣打印

2 PrintStream,字節打印流
(1)其構造函數能接受的參數:File對象、String、字節輸出流(OutputStream)

3 PrintWriter,字符打印流
(1)其構造函數能接受的參數:File對象、String、字節輸出流(OutputStream)、字符輸出流(Writer)
例子:讀取鍵盤錄入字符串,將其大寫打印在控制檯上。
代碼:

import java.io.*;
class PrintDemo 
{
	public static void main(String[] args) throws IOException
	{
		//獲取鍵盤錄入
		BufferedReader bufr=new BufferedReader(new InputStreamReader(System.in));
		//定義字符打印流,構造函數能接受字節輸出流.並且自動刷新
		PrintWriter pw=new PrintWriter(System.out,true);
		//讀取鍵盤錄入
		String line=null;
		while ((line=bufr.readLine())!=null)
		{
			//判斷結束標誌
			if("over".equals(line))
				break;
			//將讀到的數據變成大小打印出來
			pw.println(line.toUpperCase());
		}
		bufr.close();
		pw.close();
	}
}

四    管道流
1 管道流,與多線程相結合。PipedInputStream和PipedOutputStream相連。一個線程負責輸入,一個線程負責輸出。
2 例子:

import java.io.*;
//定義一個線程用於管道讀取流讀取數據
class Read implements Runnable
{
	private PipedInputStream pi;
	Read(PipedInputStream pi)
	{
		this.pi = pi;
	}
	//覆蓋run()方法
	public void run()
	{
		try
		{
			//定義一個數組接收數據
			byte[] buf = new byte[1024];
			//讀取數據
			int len = pi.read(buf);
			//打印讀到的數據
			System.out.println(new String(buf,0,len));
			//關閉資源
			pi.close();
		}
		catch (IOException e)
		{
			throw new RuntimeException("管道讀取流失敗");
		}
	}
}
//定義一個線程用於管道輸出流寫出數據
class Write implements Runnable
{
	private PipedOutputStream po;
	Write(PipedOutputStream po)
	{
		this.po = po;
	}
	public void run()
	{
		try
		{
			//寫數據
			po.write("cheng gong fa song".getBytes());
			//關閉資源
			po.close();
		}
		catch (Exception e)
		{
			throw new RuntimeException("管道輸出流失敗");
		}
	}
}

class  PipedDemo
{
	public static void main(String[] args) throws IOException
	{
		//創建管道字節輸入流
		PipedInputStream pi = new PipedInputStream();
		//創建管道字節輸出流
		PipedOutputStream po = new PipedOutputStream();
		//管道字節輸入流連接管道字節輸出流
		pi.connect(po);
		//創建線程並執行線程,輸入流負責讀,輸出流負責寫
		new Thread(new Read(pi)).start();
		new Thread(new Write(po)).start();
	}
}

五    RandomAccessFile、隨機訪問文件

1 該類不是IO體系中的子類,直接繼承Object

2 內部封裝了輸入流和輸出流,同時具備讀和寫功能,可以讀寫基本數據類型。並且只能操作文件。

3 內部封裝了一個數組,可以通過指針操作數組

4 可以通過getFilePointer方法獲取指針位置,通過seek方法設置指針位置。

5 構造函數:RandomAccessFile(String name, String mode) 
(1)構造函數可以指定模式r只讀,rw讀寫
(2)如果模式爲只讀r,則不會創建文件,會去讀取一個已存在的文件,如果文件不存在,會拋出異常
(3)如果模式爲讀寫rw,文件不存在則會創建,文件存在也不會覆蓋文件
(4)方法摘要:
writeInt(int i)  寫一個四個字節的整數
readInt(int i)   讀一個四個字節的整數
seek(int i) 設置指針位置
skipBytes(int i)  跳過i個字節

(5)例子演示:

import java.io.*;
class  RandomAccessFileDemo
{
	public static void main(String[] args) throws IOException
	{
		//write();
		read();
	}
	//定義一個功能演示讀取字節
	public static void read() throws IOException
	{
		//創建RandomAccessFile對象,模式爲只讀
		RandomAccessFile raf=new RandomAccessFile("Random.txt","r");
		//設置指針位置從24的位置開始讀
		raf.seek(8*3);
		//讀取數據
		byte[] buf=new byte[4];
		raf.read(buf);
		String name=new String(buf);
		int len=raf.readInt();
		//打印數據
		System.out.println(name+len);
		raf.close();//關閉資源
	}
	//定義一個功能演示寫入字節
	public static void write() throws IOException
	{
		//創建RandomAccessFile對象,模式爲讀寫
		RandomAccessFile raf=new RandomAccessFile("Random.txt","rw");
		//寫入數據,張三佔四個字節。int數據類型佔四個字節
		raf.write("張三".getBytes());
		raf.writeInt(15);
		//設置指針位置爲24,再開始寫入數據
		raf.seek(8*3);
		raf.write("李四".getBytes());
		raf.writeInt(16);
		//關閉資源
		raf.close();
	}
}


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