Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/main/java/org/apache/commons/io/IOUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collection;
Expand Down Expand Up @@ -3828,11 +3829,15 @@ public static void writeLines(final Collection<?> lines, final String lineEnding
* an {@link OutputStream} line by line, using the specified character
* encoding and the specified line ending.
*
* UTF-16 is written big-endian with no byte order mark.
* For little endian, use UTF-16LE. For a BOM, write it to the stream
* before calling this method.
*
* @param lines the lines to write, null entries produce blank lines
* @param lineEnding the line separator to use, null is system default
* @param output the {@link OutputStream} to write to, not null, not closed
* @param charset the charset to use, null means platform default
* @throws NullPointerException if the output is null
* @throws NullPointerException if output is null
* @throws IOException if an I/O error occurs
* @since 2.3
*/
Expand All @@ -3844,7 +3849,11 @@ public static void writeLines(final Collection<?> lines, String lineEnding, fina
if (lineEnding == null) {
lineEnding = System.lineSeparator();
}
final Charset cs = Charsets.toCharset(charset);
Charset cs = Charsets.toCharset(charset);
// don't write a BOM
if (cs == StandardCharsets.UTF_16) {
cs = StandardCharsets.UTF_16BE;
}
final byte[] eolBytes = lineEnding.getBytes(cs);
for (final Object line : lines) {
if (line != null) {
Expand Down
9 changes: 9 additions & 0 deletions src/test/java/org/apache/commons/io/IOUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1761,4 +1761,13 @@ public void testWriteLittleString() throws IOException {
}
}

@Test
public void testWriteLines() throws IOException {
final String[] data = {"The", "quick"};
final ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.writeLines(Arrays.asList(data), "\n", out, "UTF-16");
final String result = new String(out.toByteArray(), StandardCharsets.UTF_16);
assertEquals("The\nquick\n", result);
}

}