Java File Write via ByteBuffer write(Path file, String content)

Here you can find the source of write(Path file, String content)

Description

write

License

LGPL

Declaration

public static void write(Path file, String content) throws IOException 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

public class Main {
    public static void write(Path file, String content) throws IOException {
        writeBytes(file, utf8(content));
    }// w w  w  .jav  a 2 s .  co m

    @Deprecated
    public static void write(File file, String content) throws IOException {
        writeBytes(file, utf8(content));
    }

    /**
     * Writes bytes to a path
     * @param file The file to write to
     * @param bytes Bytes to write
     * @return the number of bytes written, possibly zero.
     * @throws IOException
     */
    public static int writeBytes(Path file, byte[] bytes) throws IOException {
        FileChannel channel = FileChannel.open(file, EnumSet.of(StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE));
        ByteBuffer buffer = ByteBuffer.wrap(bytes);

        channel.force(false);
        int bytesWritten = channel.write(buffer);
        channel.close();

        return bytesWritten;
    }

    @Deprecated
    public static void writeBytes(File file, byte[] bytes) throws IOException {
        File parent = file.getParentFile();
        if (parent != null && !parent.exists())
            parent.mkdirs();
        FileOutputStream out = new FileOutputStream(file);
        out.write(bytes);
        out.close();
    }

    public static byte[] utf8(String string) {
        try {
            return string.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String utf8(byte[] bytes) {
        try {
            return new String(bytes, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. mmap(File file, long offset, long length, boolean writeable)
  2. newWriteableBuffer(int capacity)
  3. write(File file, String content, String encoding)
  4. write(InputStream source, File target)
  5. write(SeekableByteChannel channel, long start, byte[] bytes)
  6. write24BitInteger(int integer, ByteOrder order)
  7. writeByte(WritableByteChannel channel, byte value)
  8. writeBytes(Path file, byte[] bytes)