Java Utililty Methods Text File Write nio

List of utility methods to do Text File Write nio

Description

The list of methods to do Text File Write nio are organized into topic(s).

Method

voidwriteFileContents(File file, String content)
write File Contents
writeFileContents(file, content, Boolean.TRUE);
voidwriteFileTxt(String fileName, String[] totalFile)
Method to get the file name (or path relative to the directory) and file to write to in the form of an array of strings where each string represents a line.
try (final Writer writer = Files.newBufferedWriter(Paths.get(fileName), Charset.forName("UTF-8"));
        PrintWriter pw = new PrintWriter(writer)) {
    for (String file : totalFile) {
        pw.println(file);
voidwriteHeader(DataOutput data, String header)
write Header
byte[] bytes = header.getBytes(Charset.forName("US-ASCII"));
data.write(bytes);
data.writeByte(NUL);
voidwriteIfSet(final OutputStream outputStream, final String field, final String value)
write If Set
if (null != value) {
    write(outputStream, field);
    write(outputStream, value);
    writeSeparator(outputStream);
voidwriteLine(final CharBuffer line, final CharBuffer output)
Copies a non-header line to the output buffer.
final String s = line.flip().toString();
if (!(s.startsWith(HEADER_BEGIN) || s.startsWith(FOOTER_END) || s.startsWith(PROC_TYPE)
        || s.startsWith(DEK_INFO) || s.trim().length() == 0)) {
    output.put(line);
line.clear();
voidwriteLines(Collection lines, File file)
write Lines
Files.write(file.toPath(), lines, StandardCharsets.UTF_8);
voidwriteLines(File file, Iterable lines)
Writes lines to a file using UTF-8, overwriting its current contents if it has any.
FileOutputStream stream = new FileOutputStream(file);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, StandardCharsets.UTF_8),
        BUFFER_SIZE);
try {
    for (String line : lines) {
        writer.write(line);
        writer.write('\n');
} catch (IOException x) {
    throw x;
} finally {
    try {
        stream.close();
    } catch (IOException x) {
voidwriteLines(String fileName, String[] lines)
Writes the lines into the file
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(new FileOutputStream(fileName), Charset.defaultCharset()));
for (int i = 0; i < lines.length; i++) {
    writer.write(lines[i]);
    writer.newLine();
writer.flush();
writer.close();
...
voidwriteLinesToFile(final File file, final String... lines)
Write lines to a file.
try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
    for (final String line : lines) {
        writer.write(line);
        writer.write(NEW_LINE);
voidwriteString(DataOutput dataOutput, String string)
write String
if (string == null) {
    writeBytes(dataOutput, null);
} else {
    final byte[] bytes = string.getBytes(UTF_8);
    writeBytes(dataOutput, bytes);