我有一个包含大约 39000 个整数的文件,用逗号分隔,每行有 13 个整数,所以我设置了一个文件阅读器和一个扫描仪来读取和解析它,但是运行它几乎需要一个多小时。我想我可能需要使用缓冲阅读器,但不知道如何实现它。任何人都可以提出更好(更快)的方法吗?
这是我的代码:
public class ECGFilereader { // reads the ecg files from the SD card
public final static int numChannels = 12; // the data is stored in 12 channels, one for each lead
public final static int numSamples = 3000; //500 = fs so *6 for 6 seconds of data
private File file;
private Scanner scanner;
short [] [] ecg = new short [numChannels] [numSamples]; //Creates a short called ecg in which all of the samples for each channel lead will be stored
public ECGFilereader (String fname) throws FileNotFoundException
{
file = new File(Environment.getExternalStorageDirectory() +"/1009856.txt"); //accesses the ecg file from the SD card
scanner = new Scanner(file);
scanner.useDelimiter(",|\\r\\n"); //sets commas and end's of lines as separators between each int
}
public boolean ReadFile(Waveform[] waves) // sorts data into and array of an array (12 channels each containing 3000 samples)
{
for (int sample=0; sample<numSamples && scanner.hasNextInt(); sample++) //
{
scanner.nextInt();
for (int chan = 0; chan<numChannels; chan++)
{
if(scanner.hasNextInt())
ecg [chan] [sample] = (short) scanner.nextInt();
else if (scanner.hasNextLine())
{ scanner.nextLine();
}
else return false;
}
}
for (int chan=0; chan<numChannels; chan++)
waves[chan].setSignal(ecg[chan]); // sets a signal equal to the ecg array of samples for each channel
return true;
}
}
编辑:
我现在已经完全删除了扫描仪类,它可以与以下代码完美配合:
public boolean ReadFile(Waveform[] waves) // sorts data into and array of an array (12 channels each containing 3000 samples)
{
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String reader = "";
for (int sample=0; sample<numSamples; sample++){
if ((reader = in.readLine()) == null) {
break;}
else {
String[] RowData = reader.split(","); // sets the commas as separators for each int.
for (int chan=0; chan <12 && chan<RowData.length; chan++)
ecg [chan][sample]= Integer.parseInt(RowData[chan+1]); //parses each int from the current row into each channel for the ecg[]
}
}
in.close();
} catch (IOException e) {
}
for (int chan=0; chan<numChannels; chan++)
waves[chan].setSignal(ecg[chan]); // sets a signal equal to the ECG array of samples for each channel
return true;
}
}