Java File Write via ByteBuffer writeFileNIO(String txt, File fyl)

Here you can find the source of writeFileNIO(String txt, File fyl)

Description

Write a file using NIO.

License

Open Source License

Parameter

Parameter Description
txt the text to output to file.
fyl the file to write to.

Exception

Parameter Description
FileNotFoundException , IOException if something goes wrong.

Return

the number of bytes written.

Declaration

public synchronized static int writeFileNIO(String txt, File fyl) throws FileNotFoundException, IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import java.nio.channels.WritableByteChannel;

public class Main {
    /**/*  ww  w .j  a v  a2  s . co m*/
     * Write a file using NIO.
     * @param txt the text to output to file.
     * @param fyl the file to write to.
     * @return the number of bytes written.
     * @throws FileNotFoundException, IOException if something goes wrong.
     */
    public synchronized static int writeFileNIO(String txt, File fyl) throws FileNotFoundException, IOException {

        return writeFileNIO(txt.getBytes(), fyl);

    }

    /**
     * Write a file using NIO.
     * @param bites the array of bytes to output to file.
     * @param fyl the file to write to.
     * @return the number of bytes written.
     * @throws FileNotFoundException, IOException if something goes wrong.
     */
    public synchronized static int writeFileNIO(byte[] bites, File fyl) throws FileNotFoundException, IOException {

        int numWritten = 0;

        // Open the file and then get a channel from the stream.
        WritableByteChannel wbc = new FileOutputStream(fyl).getChannel();

        // Allocate a buffer the size of the output and load it with the text
        // bytes.
        ByteBuffer bfr = ByteBuffer.allocateDirect(bites.length + 256);
        bfr.put(bites);

        // Set the limit to the current position and the position to 0
        // making the new bytes visible for write ().
        bfr.flip();

        // Write the bytes to the channel.
        numWritten = wbc.write(bfr);

        // Close the channel and the stream.
        wbc.close();

        // Return the number of bytes written.
        return numWritten;

    }
}

Related

  1. writeFile(File file, byte[] bytes)
  2. writeFile(File file, byte[] data)
  3. writeFile(String source, File outputFile)
  4. writeFileAsByteArray(File file, byte[] par2Data)
  5. writeFileAsStringArray(File file, String[] par2DataArray)
  6. writeFloat(OutputStream os, float val, ByteOrder bo)
  7. writeInt(OutputStream os, int val, ByteOrder bo)
  8. writeInt(OutputStream out, ByteOrder order, int i)
  9. writeInt(OutputStream out, int i)