Here you can find the source of writeBytes(Path file, byte[] bytes)
Parameter | Description |
---|---|
file | The file to write to |
bytes | Bytes to write |
Parameter | Description |
---|---|
IOException | an exception |
public static int writeBytes(Path file, byte[] bytes) throws IOException
//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 { /**//ww w .j av a 2 s . c om * 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 void write(Path file, String content) throws IOException { writeBytes(file, utf8(content)); } @Deprecated public static void write(File file, String content) throws IOException { writeBytes(file, utf8(content)); } 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; } } }