Version 2 of A Java class for reading MaCH dosage files
import java.io.*;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
/**
* Created by vu.co.kaiyin.ReadMachDosage on 15/11/14.
*/
public class Dosage {
final String filename;
final Pattern splitPattern;
public Dosage(String filename) throws Exception {
this.filename = filename;
splitPattern = Pattern.compile("\\s+");
}
public double[][] readCols(int start, int end) throws IOException {
try(
InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader reader = new InputStreamReader(gzipStream, "US-ASCII");
BufferedReader bufferedReader = new BufferedReader(reader);
) {
String line;
String[] fields;
ArrayList<double[]> dosageList = new ArrayList<>();
boolean firstLine = true;
int nCol;
while ((line = bufferedReader.readLine()) != null) {
fields = splitPattern.split(line);
if(firstLine) {
nCol = fields.length - 2;
// Data indices: x x 1 2 3
// Indices: 0 1 2 3 4
// Columns: 1->241 DOSE 1.1783 0.3498 1.9834 ...
if(start < 1) start = 1;
if(end > nCol) end = nCol;
start++;
end += 2; // java end index is exclusive
firstLine = false;
}
double[] dosage = new double[end - start];
for (int i = start; i < end; i++) {
dosage[i - start] = Double.parseDouble(fields[i]);
}
dosageList.add(dosage);
}
double[][] dosageMatrix = new double[dosageList.size()][];
dosageMatrix = (double[][]) dosageList.toArray(dosageMatrix);
return dosageMatrix;
}
}
public double[][] readAll() throws Exception {
return readCols(1, Integer.MAX_VALUE);
}
}
Changes:
- Read the file only once
- Removing unused fields
- Bug fixes in array elements assignment
- More specific exceptions