Assuming that ,
is also a decimal separator .
it may be possible to unify this characters (replace ,
with .
).
static void readAndWriteNumbers(String inputFile, String intNums, String dblNums) throws IOException {
// Use StringBuilder to collect the int and double numbers separately
StringBuilder ints = new StringBuilder();
StringBuilder dbls = new StringBuilder();
Files.lines(Paths.get(inputFile)) // stream of string
.map(str -> str.replace(',', '.')) // unify decimal separators
.map(str -> {
Arrays.stream(str.split("\\s+")).forEach(v -> { // split each line into tokens
if (v.contains(".")) {
if (dbls.length() > 0 && !dbls.toString().endsWith(System.lineSeparator())) {
dbls.append(" ");
}
dbls.append(v);
}
else {
if (ints.length() > 0 && !ints.toString().endsWith(System.lineSeparator())) {
ints.append(" ");
}
ints.append(v);
}
});
return System.lineSeparator(); // return new-line
})
.forEach(s -> { ints.append(s); dbls.append(s); }); // keep lines in the results
// write the files using the contents from the string builders
try (
FileWriter intWriter = new FileWriter(intNums);
FileWriter dblWriter = new FileWriter(dblNums);
) {
intWriter.write(ints.toString());
dblWriter.write(dbls.toString());
}
}
// test
readAndWriteNumbers("test.dat", "ints.dat", "dbls.dat");
Output
//ints.dat
1 2 3 4 5
1 3 4 5 8
// dbls.dat
4.5 4.6 6.8 8.9
9.2 6.3 6.7 8.9