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

  • 相关阅读:
    php页面调用微信扫一扫
    mysql大数据表添加字段
    Maven使用本地包的打包和安装(举例微信SDK)
    谈谈统计学正态分布阈值原理在数据分析工作中的运用
    深入剖析 RSA 密钥原理及实践
    Kafka 原理以及分区分配策略剖析
    jenkins+docker实现自动编译、打包、构建镜像、容器部署
    php7安装ldap扩展
    jenkins 简单实现php集成上线部署
    Jenkins 流水线(Pipeline)
  • 原文地址:https://www.cnblogs.com/CBDoctor/p/4080143.html
Copyright © 2011-2022 走看看