Here you can find the source of writeFileNIO(String txt, File fyl)
Parameter | Description |
---|---|
txt | the text to output to file. |
fyl | the file to write to. |
Parameter | Description |
---|---|
FileNotFoundException | , IOException if something goes wrong. |
public synchronized static int writeFileNIO(String txt, File fyl) throws FileNotFoundException, IOException
//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; } }