JAVA文件的两种读取方法和三种写入方法

时间:2023-03-08 15:54:43
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();
}