This code only directly references 1 line from each file in RAM at a time, meaning it should work with huge files without memory exceptions. Behind the scenes more memory may be occupied than what you see, but it will still not crash with huge files.
Code works by reading one line at a time from each of the files till all files are empty. As files run out of lines output an empty string instead.
void assignment(String outputFile, String... filenames){
PrintWriter writer = new PrintWriter(outputFile, "UTF-8");
Scanner scanners = new Scanner[filenames.length];
for(int i=0;i<filenames.length;i++){
Scanner scanner = new Scanner(new File(filenames[i]));
scanners[i] = scanner;
}
boolean running = true;
while(running){
boolean allEmpty = true;
StringBuilder csvLine = new StringBuilder();
for(int i=0;i<scanners.lengh;i++){
if(scanner.hasNextLine()){
String line = scanner.nextLine();
csvLine.append(line);
allEmpty=false;
}
if(i!=scanners.length-1) csvLine.append(",");
}
if(allEmpty)
running=false;
else
writer.println(csvLine.toString());
}
writer.close();
for(Scanner s : scanners) s.close();
}
Usage:
assignment("output.txt","file1.txt","file2.txt","file3.txt","file4.txt");
Or:
String[] args = new String[]{"helloWorld.txt","fun.bin"};
assignment("output2.txt",args);
This code is untested and doesn't handle exceptions. This code will let you read in lines from files who's lines don't match, and combine them into a single CSV file. As files run out of lines, only empty strings will be shown.
This should give you an idea of how to do precisely what you've asked.