In this post under Apache Commons IO, I will show with example the purpose of “writeLines” static method available in “IOUtils” class
“writeLines” method takes a list of Objects and writes them to outputstream or writer.
For each object to be written, it calls its “toString” method to get the String representation of the object before writing it.
The “writeLines” method takes three arguments
1) collection of objects to be written
2) line separator to be used. null to use system default
3) the outputstream or writer object.
For our example I will write collection of string to a file.
Below is the complete main code for your reference
Main class
package ioutils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Example12 {
public static void main(String[] args) throws IOException {
List<String> lines = new ArrayList<>();
lines.add("No man is a true believer unless he desires for his brother that which he desires for himself. -Prophet");
lines.add("Character is easier kept than recovered - The International");
lines.add("The created must sometimes protect the creator - even against his will - I Robot");
File file = new File("Output.txt");
try(FileWriter fileWriter = new FileWriter(file)) {
IOUtils.writeLines(lines, null, fileWriter);
}
}
}
In the above code, first I define and populate the collection “lines”.
Then I write entries of the collection to the file “Output.txt” using “writeLines” method.
In this way we can use “writeLines” static method of “IOUtils” class.