Java文件读取

常见的文件读取方式:

public class ReadFile{
	
	public void readFileByBytes(String fileName){
		
		File file = new File(fileName);
		InputStream in = null;
		try{
			
			in = new FileInputStream(file);
			int tmpByte = 0;
			while((tmpByte = in.read())!=-1){
				System.out.println(tmpByte);
			}
		
		}catch(IOException e){
			
		}finally{
			if (in != null) {  
                try {  
                    in.close();  
                } catch (IOException e1) {  
                }  
            }  
		}
		
		try{
			
			byte[] bytes = new byte[100];
			int rd = 0;
			in = new FileInputStream(file);
			while((rd = in.read(bytes)) != -1){
				System.out.write(bytes, 0, rd);
			}
			
		}catch(IOException e){
			
		}finally{
			if (in != null) {  
                try {  
                    in.close();  
                } catch (IOException e1) {  
                }  
            }  
		}	
	}
	
	public void readFileByChars(String fileName){
		
		File file = new File(fileName);
		Reader reader = null;
		try{
			reader = new InputStreamReader(new FileInputStream(file));
			int tmpChar = 0;
			while((tmpChar = reader.read()) != -1){
				if (((char) tempchar) != '\r') {  
                    System.out.print((char) tempchar);  
                }  
			}
		}catch(Exception e){
			
		}finally{
			if (reader != null) {  
                try {  
                    reader.close();  
                } catch (Exception e1) {  
                }  
            }  
		}
		
		try{
			
			char[] tmp = new char[30];
			int rd = 0;
			reader = new InputStreamReader(new FileInputStream(file));
			
			while((rd = reader.read(tmp)) != -1){
				if ((rd == tmp.length)  
                        && (tmp[tmp.length - 1] != '\r')) {  
                    System.out.print(tmp);  
                } else {  
                    for (int i = 0; i < rd; i++) {  
                        if (tmp[i] == '\r') {  
                            continue;  
                        } else {  
                            System.out.print(tmp[i]);  
                        }  
                    }  
                }  
			}
		}
		
		
	}
	
	public void readFileByLines(String fileName){
		
		File file = new File(fileName);
		BufferedReader reader = null;
		
		try{
			reader =  new BufferedReader(new FileReader(file));
			String line = null;
			while((line = reader.readLine())!= null){
				System.out.println(line);
			}
		}catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (reader != null) {  
                try {  
                    reader.close();  
                } catch (IOException e1) {  
                }  
            }  
        }  	
	}
	
	public void readFileByRandomAccess(String fileName){
		
		RandomAccessFile randomFile = null;
		
		try{
			randomFile = new RandomAccessFile(fileName,"r");
			long fileLength = randomFile.length();
			int benginIndex = (fileLength > 4) ? 4 : 0;
			
			randomFile.seek(benginIndex);
			byte[] bytes = new byte[100];
			int rd = 0;
			while((rd = randomFile.read(bytes))!=-1){
				System.out.write(bytes, 0, rd);
			}
		}catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (randomFile != null) {  
                try {  
                    randomFile.close();  
                } catch (IOException e1) {  
                }  
            }  
        }  
	}
}

借助工具类读取文件

commons.io 操作
    
    输入流复制到 输出流 
    IOUtils.copy(ins, write);  
    
    文本写入指定文件 
    FileUtils.writeStringToFile(file, name);  
    
    将输入流转换成文本
    String contents = IOUtils.toString(ins,"UTF-8");  
    
    文件复制
    FileUtils.copyFile(srcfile, destfile); 
    
    文件复制指定的目录 
    File srcfile = new File("c:\\Test.java");  
    File destDir = new File("D:\\");  
    FileUtils.copyFileToDirectory(srcfile, destDir);  
    
    网络流保存为文件
    URL url = new URL("http://www.163.com");  
    File file = new File("c:\\163.html");  
    FileUtils.copyURLToFile(url, file);
    
    文件目录操作 
    FileUtils.cleanDirectory(dir);//清空目录下的文件  
    FileUtils.deleteDirectory(dir);//删除目录和目录下的文件

与之对应的,还有gvava中对文件的操作工具类File.

但是有一个问题,这些对文件的操作都是将文件全部加载到内存中,如果文件过大,会导致内存溢出。通常不需要把文件的所有行一次性地放入内存中,只需要遍历文件的每一行,然后做相应的处理,处理完之后把它扔掉。

public class ReadFile{
	
	public void readFileByScanner(String fileName){
		// 通过Java util
		InputStream ins = null;
		Scanner sc = null;
		try{
			ins = new FileInputStream(new File(fileName));
			sc = new Scanner(ins, "UTF-8");
			while(sc.hasNextLine()){
				String line = sc.nextLine();
		
			}
			
		}finally{
			if(ins != null){
				ins.close();
			}
			
			if(sc != null){
				sc.close();
			}
		}
		
		
		// 通过Commons io
		
		LineIterator it = FileUtils.lineIterator(new File(fileName), "UTF-8");
		
		try{
			while(it.hasNext()){
				String line = it.nextLine();
			}
		}finally{
			LineIterator.closeQuietly(it);
		}
	}
	
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值