zoukankan      html  css  js  c++  java
  • JAVA文件的两种读取方法和三种写入方法

    在使用java对文件进行读写操作时,有多种方法可以使用,但不同的方法有不同的性能。

    此文对常用的读写方法进行了整理,以备不时之需。

    1、文件的读取

    主要介绍两种常用的读取方法。按行读取和按字符块读取。

    1.1 一次读取一行作为输入

    //按行读取文件内容
    	public static String Read1(String infile)	throws Exception	//infile="data/in.txt"
    	{
    		StringBuffer sb = new StringBuffer();
    		
    		BufferedReader br = new BufferedReader(new FileReader(infile));
    		String data = br.readLine();
    		while(data != null)
    		{
    			sb.append(data+"
    ");
    			data = br.readLine();
    		}
    		br.close();
    		return sb.toString();
    	}

    1.2 一次读取指定大小的字符块

             关于一次读取一个字符的方法就不讲了,感觉这种方法效率太低了!

    //以字符块读取文件
    	public static String Read2(String infile) throws Exception
    	{
    		StringBuffer sb = new StringBuffer();
    		
    		File file = new File(infile);
    		FileInputStream fis = new  FileInputStream(file);
    		byte buffer[] = new byte[1024];
    		int len = 0;
    		while((len = fis.read(buffer)) != -1)
    		{
    			sb.append(new String(buffer, 0, len));
    			//sb.append(new String(buffer, 0, len, "UTF-8"));	//将byte转String可以指定编码方式
    		}
    		fis.close();
    		return sb.toString();
    	}

    2、文件的写入

    关于文件的写入,主要有三种方法,分别使用FileWriter、FileOutputStream和BufferedOutputStream。

    根据一个网友的测试结果,在这三种方法中,使用FileWriter速度最快,而使用FileOutputStream速度最慢。


    2.1 使用FileWriter函数写入数据到文件

    //性能最好
    	public static void Write1(String file, String text) throws Exception
    	{
    		FileWriter fw = new FileWriter(file);
    		fw.write(text, 0, text.length());		//fw.write(text)
    		fw.close();
    	}
    2.2 使用FileOutputStream函数写入

    //三种方法中性能最弱
    	public static void Write2(String file, String text)	throws Exception
    	{
    		FileOutputStream fos = new FileOutputStream(file);
    		fos.write(text.getBytes());
    		fos.close();
    		
    		//PrintStream ps = new PrintStream(fos);
    		//ps.print(text);
    		//ps.append(text);
    	}


    2.3 使用BufferedOutputStream函数写入

    //这三种方法中,性能中等
    	public static void Write3(String file, String text)	throws Exception
    	{
    		BufferedOutputStream buff = new BufferedOutputStream(new FileOutputStream(file));
    		buff.write(text.getBytes());
    		buff.flush();
    		buff.close();
    	}


  • 相关阅读:
    SilverLight入门实例(一)
    应聘成功了,要去沪江网上班啦!
    C#中(int)、int.Parse()、int.TryParse、Convert.ToInt32数据转换注意事项
    DataTable和DataSet什么区别
    SQL 通配符
    可以把 SQL 分为两个部分:数据操作语言 (DML) 和 数据定义语言 (DDL)
    发现jquery库的关键字冲突,造成了隐形BUG!(附代码)
    《转载》微软PostScirpt打印机驱动程序原理
    在应聘工作中,不知不觉的完成了一个比较困难的小项目
    在最新的Eclipse 3.6 上配置 Java ME 的开发环境!
  • 原文地址:https://www.cnblogs.com/liuwu265/p/4100093.html
Copyright © 2011-2022 走看看