Java 對文件的操做

public class ReadFile {
	
	/**
	 * 按行讀取文件操做
	 * @throws IOException 
	 */
	public void readFile(String fileName) throws IOException{
		//(1)File 類
		File file = new File(fileName);
		//
		BufferedReader reader = null;
		try {
			//(2) 將文件放入到BufferedReader中
			reader  = new BufferedReader(new FileReader(file));
			String temp = null;
			int line = 0;
			while( (temp = reader.readLine()) != null){
				System.out.println(temp + (++line));
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			reader.close();
		}
			
	}
	
	/**
	 * 文件的寫入操做
	 */
	public void writeFile(String fileName, String str) throws IOException{
		
		
		File file = new File(fileName);
		//true實現對文件的追加操做
		FileWriter ws = new FileWriter(file,true);
		
		ws.write(str);
		
		ws.close();
		
	}
	
	/**
	 * 對於一個大文本文件,咱們僅僅讀取最後的N行
	 * @throws IOException 
	 */
	public String[] getLastNFromFile(String fileName) throws IOException{
		
		String []temp = new String[5];
		File f = new File(fileName);
		BufferedReader reader = new BufferedReader(new FileReader(f));
		String temp1 = null;
		int line = 0;
		while((temp1 = reader.readLine()) != null){
			temp[line++]= temp1;
			if(line >= 5 ){
				line = 0;
			}
		}
		
		return temp;
		
		
	}
	
	/**
	 * 經過索引進行操做
	 * @throws IOException 
	 */
	public String[] getLastNFromFileByIndex(String fileName) throws IOException{
		
		String []temp = new String[5];
		File f = new File(fileName);
		BufferedReader reader = new BufferedReader(new FileReader(f));
		String temp1 = null;
		int line = 0;
		while((temp1 = reader.readLine()) != null){
			line++;
		}
		
		return temp;
		
		
	}
	
	
	

}

  對2000000行的文件進行操做,讀取最後的5行,並無發現直接經過行索引和經過一個數組進行棧式進入有什麼差異!數組

相關文章
相關標籤/搜索