You can use the Java 8 API to manipulate integer arrays and write lines into a file. In my opinion, it's easier and cleaner.
The process of writing all the lines into a file is just one line of code (assuming that you don't load super large amount of data into the memory all at once):
void writeLines(Path file, List<String> lines) throws IOException {
Files.write(file, lines, StandardOpenOption.APPEND);
}
Explanation and an example
Let's suppose you have a method that provides you with a list of integer arrays:
List<int[]> getIntArrays() {
int[] a1 = { 23, 54, 656, 332, 556 };
int[] a2 = { 12, 45, 6556, 232, 323 };
int[] a3 = { 898, 787, 23, 4545, 233 };
return Arrays.asList(a1, a2, a3);
}
You can convert each array into a one-line string this way:
String toString(int[] array) {
String DELIMITER = " ";
return String.join(DELIMITER, IntStream.of(array)
.mapToObj(a -> String.valueOf(a))
.collect(Collectors.toList()));
}
The next method converts a list of integer arrays into a list of strings:
List<String> toString(List<int[]> arrays) {
return arrays.stream().map(a -> toString(a)).collect(Collectors.toList());
}
This list can be fed to the writeLines
method above and the lines will be written to a file.
How do we write the header?
Here's a full example. It writes the header add all the lines of integers.
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ArrayWriter {
private final static Charset UTF8 = Charset.forName("UTF-8");
private final static String DELIMITER = " ";
public static void main(String[] args) throws IOException {
Path file = Paths.get("test.txt");
writeHeader(file);
writeLines(file, toString(getIntArrays()));
}
private static void writeHeader(Path file) throws IOException {
String line = String.join(DELIMITER, getHeader());
Files.write(file, Arrays.asList(line), UTF8, StandardOpenOption.CREATE);
}
private static void writeLines(Path file, List<String> lines) throws IOException {
Files.write(file, lines, UTF8, StandardOpenOption.APPEND);
}
private static List<String> toString(List<int[]> arrays) {
return arrays.stream().map(a -> toString(a)).collect(Collectors.toList());
}
private static String toString(int[] array) {
return String.join(DELIMITER,
IntStream.of(array).mapToObj(a -> String.valueOf(a)).collect(Collectors.toList()));
}
public static String[] getHeader() {
return new String[] { "A", "B", "C", "D", "E" };
}
public static List<int[]> getIntArrays() {
int[] a1 = { 23, 54, 656, 332, 556 };
int[] a2 = { 12, 45, 6556, 232, 323 };
int[] a3 = { 898, 787, 23, 4545, 233 };
return Arrays.asList(a1, a2, a3);
}
}