我在CodeEval上做了一些任務。基本上,任務非常簡單:「打印出從文件中讀取的所有整數的總和」。如何從性能問題的文件中讀取整數?
我的解決方案如下:
import java.io.File;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
public class SumIntegersFromFile {
public static void main(String args[]) throws IOException{
File file = new File(args[0]);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i=0;
while((line=br.readLine())!=null){
int k = Integer.parseInt(line);
i+=k;
}
br.close();
System.out.println(i);
}
}
但有人告訴我,這個解決方案不是從性能上看最佳。
該代碼基於問題Best way to read a text file中的建議。唯一的區別是我讀的是整數而不是字符串。
從Java中的文件中讀取整數的性能最有效的方法是什麼?
「我從35中只得到29.352」是什麼意思? – BitNinja 2014-08-31 20:11:27
這個問題似乎是無關緊要的,因爲它是關於改進工作代碼。嘗試在[codereview.se]上發佈。 – Keppil 2014-08-31 20:14:17
@BitNinja我的意思是分數,最高分是35,我得到29.352 – 2014-08-31 20:16:57