This class reads a delimited text file into String arrays on demand. Delimiter can be any regex.
Features include:
Read a single column
Read a range of columns
Read arbitrary columns by providing an array of indices, e.g. for columns 1, 3, 5, use
new int[]{1, 3, 5}
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Created by IDEA on 17/11/14.
*/
public class Txt {
final private String sep;
final private Pattern pattern;
final private String filename;
private Supplier<Stream<String>> fileStream;
Txt(String _filename, String _sep) throws IOException {
sep = _sep;
filename = _filename;
pattern = Pattern.compile(sep);
fileStream = () -> {
try {
return Files.lines(Paths.get(filename), Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
return null;
}
};
}
Txt(String _filename) throws IOException {
this(_filename, "\\s+");
}
public String[] nthCol(int n) throws IOException {
if(n < 1) n = 1;
final int finalN = n;
List<String> colList = fileStream.get()
.map(line -> pattern.split(line, finalN + 1)[finalN - 1])
.collect(Collectors.toList());
return colList.toArray(new String[colList.size()]);
}
public String[][] cols() throws IOException {
List<String[]> colsList = fileStream.get()
.map(line -> pattern.split(line))
.collect(Collectors.toList());
return colsList.toArray(new String[colsList.size()][]);
}
public String[][] cols(final int start, final int end) {
if(start > end || start < 1) throw new IllegalArgumentException("Starting index must <= ending index AND >= 1");
List<String[]> colsList = fileStream.get()
.map(line -> {
String[] fields = pattern.split(line, end + 1);
// indices of col 2-4 2 3 4
// fields after splitting 0 1 2 3 4
// range of array 1 4
// java ending index is exclusive
String[] demandedFields = Arrays.copyOfRange(fields, start-1, end);
return demandedFields;
})
.collect(Collectors.toList());
return colsList.toArray(new String[colsList.size()][]);
}
public String[][] cols(int[] index) {
Arrays.sort(index);
final int[] finalIndex = index;
final int start = finalIndex[0];
final int end = finalIndex[finalIndex.length - 1];
if(start > end || start < 1) throw new IllegalArgumentException("Starting index must <= ending index AND >= 1");
List<String[]> colsList = fileStream.get()
.map(line -> {
String[] fields = pattern.split(line, end + 1);
String[] demandedFields = new String[finalIndex.length];
for(int i=0; i<finalIndex.length; i++) {
demandedFields[i] = fields[finalIndex[i]-1];
}
return demandedFields;
})
.collect(Collectors.toList());
return colsList.toArray(new String[colsList.size()][]);
}
}