【发布时间】:2013-12-22 20:49:39
【问题描述】:
所以我有一个能够读取 csv 文件的工作代码,但由于文件非常大,因此在所有数据立即显示在 textarea 中之前,大约需要两分钟才能读取。我在 Eclipse 中使用带有 windowsbuilder 的 GUI 界面。下面是代码;
JButton btnopen = new JButton("Open");
btnopen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
final JFileChooser fc = new JFileChooser(); //launching the file chooser
fc.setFileFilter(new FileNameExtensionFilter("Text Files", "txt")); //this will allow text files to be read
fc.setFileFilter(new FileNameExtensionFilter("CSV", "csv")); //this will allow csv files to be read
fc.setFileFilter(new FileNameExtensionFilter("JSON", "json")); //this will allow json files to be read
fc.setFileFilter(new FileNameExtensionFilter("XML", "xml")); //this will allow xml files to be read
int returnVal = fc.showOpenDialog(contentPane);
File f; //file that holds the data from the text file
fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter());
if(returnVal == JFileChooser.APPROVE_OPTION) {
f = fc.getSelectedFile(); //tells file chooser to get the file selected and store into file variable
String output="";
//use buffered reader and file reader to read selected file
BufferedReader in = new BufferedReader(new FileReader(f));
//after reading data, store in to string
String line = in.readLine(); //every time a line is read, data is put into text area
int i=0;
while(line!=null){ //while still reading...
//
line = in.readLine(); //continue reading next line of file
output +=line+"\n";
//textArea.append(line +"\n"); //add text from file into text area
//++i;
}
textArea.append(output);
}
}
catch(Exception e){
}
}
});
【问题讨论】:
-
那么你的问题是什么?
-
使用 StringBuilder 构建字符串而不是 output+=line;
-
@HectorLector 你能否告诉我如何在我的代码中实现它。我是新手,所以我对 java 并不完全有信心。
-
@SpacePope 我的问题是,我想知道我目前的代码是否有任何改进,可以更快地读取 csv 文件。
-
要将整个文件内容读入字符串,您可以使用: String fullFile = new String(Files.readAllBytes(f.toPath()));您正在阅读的文件的大小是多少?
标签: java eclipse csv windowbuilder