zoukankan      html  css  js  c++  java
  • 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行,并没有发现直接通过行索引和通过一个数组进行栈式进入有什么差别!

  • 相关阅读:
    查看日志
    MySQL连接方式和启动方式
    day03--MySQL用户篇
    MySQL5.6与5.7区别
    Ansible部署主从复制
    day03--MySQL多实例及多实例主从
    MySQL体系结构
    day02-mysql编译安装误删除用户恢复
    数据库包获取方式
    day01--数据库介绍及二进制安装MySQL5.6
  • 原文地址:https://www.cnblogs.com/CBDoctor/p/4080143.html
Copyright © 2011-2022 走看看