java中對文件的操作

A:字節流

一:我們應該建立文件 

,在這其實文件夾和文本文件都是文件,只是文件夾是一個特殊的文件,這句話我們已經建立了一個文件對象,可以對file操作,查找它的路徑,字節長度,同時我們注意在操作系統中分配的最小區間是4kb。

對於讀文件:我們應該新建一個要讀 的對象,爲了讀取,我們必須建立管道,在讀出來的是字節數組,要用String 轉化以下。在這裏a充當了一個緩存的作用,讀入內存時 ,我們應該先將其讀入a中,當a滿了,或讀完了,就可以放入內存。

File file=new File("E:/html/logo.txt");//建對象
FileInputStream in=new FileInputStream(file);//建管道
int n=0;
byte[]  a=new byte[1024];//數據長度一般爲1024個長度
while((n=in.read(a))!=-1)//將n讀入數據a中
				{
					String str=new String(a,0,n);//不用這句可能會出亂,因爲a是1024System.out.println(str);}對於一些文件的基本操作

判斷是否存在,若不存在就新建。

File file=new File("E:/html5/test.txt");
		if(!file.exists())
		{
			file.createNewFile();
		}



判斷是否存在文件夾,若不存在就新建。

File file=new File("D:/test");
if(!file.isDirectory())
{

   file.mkdir();
}


列出文件夾下的所有文件

if(file.isDirectory())
		{
			File[] file1=file.listFiles();
			for(int i=0;i<file1.length;i++)
			System.out.println(file1[i].getName());
		}


二:注意文件中的寫 ,關閉

我們應該在讀取完畢關閉文件,關閉文件時應該注意, 要將其放到finally{}中。

寫文件與讀文件一樣,我們應該建立文件,建立通道。

File file=new File("E:/html5.txt");
		FileOutputStream out=null;
out=new FileOutputStream(file);
			String b="asdad";
out.write(b.getBytes());


三,讀取圖片文件,並寫入另一個圖片文件,注意在此 用的是字符流,不能用字節流 。

File file=new File("E:/html/logo.jpg");
		File file1=new File("D:/logo.jpg");
		try {
			FileInputStream in=new FileInputStream(file);
			FileOutputStream out=new FileOutputStream(file1);
			int n=0;
			byte[]  a=new byte[1024];
			try {
				while((n=in.read(a))!=-1)
				{
					String str=new String(a,0,n);
					out.write(a);
					//System.out.println(str);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

B:字符流(與上同理)

FileReader fr=new FileReader(file);

C:緩衝字節流 ,有一個最好的方法,也是提高效率的方法是按行 讀取!

FileReader file=new FileReader("E:/html/logo.txt");
BufferedReader buf=new BufferedReader(file);
buf.readLine();
他讀出的是String,不要再定義一個字節,或字符了!其他不變


發佈了60 篇原創文章 · 獲贊 7 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章