public void importLineData(String dbid, File f, double ddd){
if(f.exists() && f.isFile() && f.length()>0){
try {
RandomAccessFile raf = new RandomAccessFile(f,"r");
int count = 0;
while (raf.getFilePointer() < raf.length()) {
String temp = raf.readLine();
String d = new String(temp.getBytes("ISO-8859-1"),"UTF-8");
while(!d.endsWith(");")){
temp = raf.readLine();
d += new String(temp.getBytes("ISO-8859-1"),"UTF-8");
}
String sql = d.substring(0, d.length()-1);
count++;
}
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void importLineData(String dbid, File f, int startLine){
if(f.exists() && f.isFile() && f.length()>0){
try {
Scanner sc = new Scanner(f);
int count = 0;
while(sc.hasNextLine()){
String temp = sc.nextLine();
String d = new String(temp.getBytes("ISO-8859-1"),"UTF-8");
while(!d.endsWith(");")){
temp = sc.nextLine();
d += new String(temp.getBytes("ISO-8859-1"),"UTF-8");
}
String sql = d.substring(0, d.length()-1);
count++;
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上两个方法去读取同一个文件,使用Scanner按行读取文件效率高好多好多倍,内存占用高一点点而已;而使用RandomAccessFile按行读取数据效率极低,推荐使用Scanner。
RandomAccessFile类。其I/O性能较之其它常用开发语言的同类性能差距甚远,严重影响程序的运行效率。
在改进之前先做一个基本测试:逐字节COPY一个12兆的文件(这里牵涉到读和写)。
读 | 写 | 耗用时间(秒) |
RandomAccessFile | RandomAccessFile | 95.848 |
BufferedInputStream + DataInputStream | BufferedOutputStream + DataOutputStream | 2.935 |
我们可以看到两者差距约32倍,RandomAccessFile也太慢了。由其源码可见,RandomAccessFile每读/写一个字节就需对磁盘进行一次I/O操作。