[英]Existing file slowing down java program
我正在一起運行一些方法,這些方法可以接收許多文本文件,讀取它們的內容,然后將有關其內容的內容寫到一個新文件中。 我的問題是,當文件存在時,程序速度很慢。 如果刪除文件並運行程序,則速度非常快。 我為我的I / O使用BufferedReader和BufferedWriter。 我覺得我沒有找到一個簡單的答案。 提前致謝! 如果可能的話,我寧願不發布代碼,對不起!
編輯:
這是一般情況
File path= new File("some path");
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(path, false));
//do some string manipulation
writer.append(string);
writer.newLine();
...
//once done
writer.close();
}catch(IOException e) {
//... handle this ...
}
問題在於,當該文件存在時,一切都會變慢。 如果沒有,那就快了。
當您說“ //做一些字符串操作”時,我將重新審視您的工作。
這是我通過> 1000次迭代發現的:
我還做了一個此測試的版本,該文件始終總是首先被刪除。 沒關系。 這是我運行的代碼:
public static void main(String[] args) {
long s = System.currentTimeMillis();
File path = new File("output.txt");
long stop = System.currentTimeMillis();
System.out.println("handle acquired " + (stop - s) );
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(path, false));
//do some string manipulation
s = System.currentTimeMillis();
for (int i =0; i < 10000000; i++) {
String string = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
writer.append(string);
writer.newLine();
}
stop = System.currentTimeMillis();
System.out.println("loop end " + (stop - s) );
s = System.currentTimeMillis();
writer.close();
stop = System.currentTimeMillis();
System.out.println("writer closed " + (stop - s) );
}catch(IOException e) {
//... handle this ...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.