本帖最后由 王盟盟 于 2013-5-14 12:10 编辑
关于文件读写,最有效率的方法是什么?利用怎样的缓存技术能够提高大文件的读写速度?我只会用一些简单的缓存技术,比如下面这些怎么优化会更好?
import java.io.*;
import javax.swing.ProgressMonitorInputStream;
public class FileTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
file1 f=new file1();
}
}
class file1
{
File a=new File("d:\\a.txt");
File b=new File("d:\\b.txt");
public file1()
{
//调用字节流函数
fileStream();
//调用字符流函数
// fileRandW();
//调用缓冲字符流函数
//fileBuffered();
}
//利用fileInputStream,file outputStream字节流
private void fileStream()
{
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream(a);
fos=new FileOutputStream(b);
ProgressMonitorInputStream pp=new ProgressMonitorInputStream(null,"Reading"+a.getName(),fis);
byte bytes[]=new byte[1024];
int n=0;
if(a.exists())
{
while((n=fis.read(bytes))!=-1)
{
if(b.exists())
{
fos.write(bytes);
}
else
{
b.createNewFile();
fos.write(bytes);
}
}
}else
{
System.out.println("文件不存在");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
fis.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//利用fileReader,fileWriter字符流
private void fileRandW()
{
FileReader fr=null;
FileWriter fw=null;
try {
fr=new FileReader(a);
fw=new FileWriter(b);
char []chars=new char[1024];
int n=0;
if(a.exists())
{
while((n=fr.read(chars))!=-1)
{
if(b.exists())
{
fw.write(chars);
}else
{
b.createNewFile();
fw.write(chars);
}
}
}
else
{
System.out.println("文件不存在");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
fr.close();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//利用BufferedReader,BufferedWriter 缓冲字符流
private void fileBuffered()
{
FileReader fr=null;
FileWriter fw=null;
BufferedReader br=null;
BufferedWriter bw=null;
try {
fr=new FileReader(a);
fw=new FileWriter(b);
br=new BufferedReader(fr);
bw=new BufferedWriter(fw);
int n=0;
int times=0;
String s="";
if(a.exists())
{
while((s=br.readLine())!=null)
{
System.out.println(s);
if(b.exists())
{
bw.write(s+"\r\n");
}else
{
b.createNewFile();
bw.write(s+"\r\n");
}
times++;
}
System.out.println(times);
}else
{
System.out.println("文件不存在");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
br.close();
bw.close();
fr.close();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|