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+"\n");

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();

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值