如何使用java.nio.channels.FileChannel将字节[]写入文件-基础

如何使用java.nio.channels.FileChannel将字节[]写入文件-基础,java,Java,我没有使用Java通道的经验。我想将字节数组写入文件。目前,我有以下代码: String outFileString = DEFAULT_DECODED_FILE; // Valid file pathname FileSystem fs = FileSystems.getDefault(); Path fp = fs.getPath(outFileString); FileChannel outChannel = FileChannel.open(fp, EnumSet.of(Standar

我没有使用Java通道的经验。我想将字节数组写入文件。目前,我有以下代码:

String outFileString = DEFAULT_DECODED_FILE; // Valid file pathname
FileSystem fs = FileSystems.getDefault();
Path fp = fs.getPath(outFileString);

FileChannel outChannel = FileChannel.open(fp, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE));

// Please note: result.getRawBytes() returns a byte[]
ByteBuffer buffer = ByteBuffer.allocate(result.getRawBytes().length);
buffer.put(result.getRawBytes());

outChannel.write(buffer); // File successfully created/truncated, but no data
使用这段代码,将创建输出文件,如果存在,则会将其截断。此外,在IntelliJ调试器中,我可以看到
buffer
包含数据。此外,成功调用了行
outChannel.write()
,而没有引发异常。但是,程序退出后,数据不会显示在输出文件中


有人能告诉我(a)FileChannel API是否是将字节数组写入文件的可接受的选择,以及(b)如果是,应该如何修改上述代码以使其正常工作?

正如gulyan指出的,在写入字节缓冲区之前,您需要
flip()
。或者,您可以包装原始字节数组:

ByteBuffer buffer = ByteBuffer.wrap(result.getRawBytes());
要保证写入在磁盘上,您需要使用:

或者您可以关闭该频道:

outChannel.close();

正如gulyan指出的,在写入字节缓冲区之前,需要
flip()
。或者,您可以包装原始字节数组:

ByteBuffer buffer = ByteBuffer.wrap(result.getRawBytes());
要保证写入在磁盘上,您需要使用:

或者您可以关闭该频道:

outChannel.close();
你应致电:

buffer.flip();
在写之前

这将为读取准备缓冲区。 还有,你应该打电话

buffer.clear();
在将数据放入之前。

您应该调用:

buffer.flip();
在写之前

这将为读取准备缓冲区。 还有,你应该打电话

buffer.clear();

在将数据放入之前。

回答您的第一个问题

告诉我FileChannel API是否是将字节数组写入文件的可接受选择


没关系,但有更简单的方法。尝试使用
文件输出流
。通常,为了提高性能,这将由一个
缓冲输出流
包装,但关键是这两个扩展
输出流
,它有一个简单的
写入(byte[])
方法。这比通道/缓冲区API更容易使用。

回答第一个问题

告诉我FileChannel API是否是将字节数组写入文件的可接受选择


没关系,但有更简单的方法。尝试使用
文件输出流
。通常,为了提高性能,这将由一个
缓冲输出流
包装,但关键是这两个扩展
输出流
,它有一个简单的
写入(byte[])
方法。这比通道/缓冲区API更容易使用。

这里是FileChannel的完整示例

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.channels.WritableByteChannel;


    public class FileChannelTest {
        // This is a Filer location where write operation to be done.
        private static final String FILER_LOCATION = "C:\\documents\\test";
        // This is a text message that to be written in filer location file.
        private static final String MESSAGE_WRITE_ON_FILER = "Operation has been committed.";

        public static void main(String[] args) throws FileNotFoundException {
            // Initialized the File and File Channel
            RandomAccessFile randomAccessFileOutputFile = null;
            FileChannel outputFileChannel = null;
            try {
                // Create a random access file with 'rw' permission..
                randomAccessFileOutputFile = new RandomAccessFile(FILER_LOCATION + File.separator + "readme.txt", "rw");
                outputFileChannel = randomAccessFileOutputFile.getChannel();
                //Read line of code one by one and converted it into byte array to write into FileChannel.
                final byte[] bytes = (MESSAGE_WRITE_ON_FILER + System.lineSeparator()).getBytes();
                // Defined a new buffer capacity.
                ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
                // Put byte array into butter array.
                buffer.put(bytes);
                // its flip the buffer and set the position to zero for next write operation.
                buffer.flip();
                /**
                 * Writes a sequence of bytes to this channel from the given buffer.
                 */
                outputFileChannel.write(buffer);
                System.out.println("File Write Operation is done!!");

            } catch (IOException ex) {
                System.out.println("Oops Unable to proceed file write Operation due to ->" + ex.getMessage());
            } finally {
                try {
                    outputFileChannel.close();
                    randomAccessFileOutputFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }

    }

下面是FileChannel的完整示例

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.channels.WritableByteChannel;


    public class FileChannelTest {
        // This is a Filer location where write operation to be done.
        private static final String FILER_LOCATION = "C:\\documents\\test";
        // This is a text message that to be written in filer location file.
        private static final String MESSAGE_WRITE_ON_FILER = "Operation has been committed.";

        public static void main(String[] args) throws FileNotFoundException {
            // Initialized the File and File Channel
            RandomAccessFile randomAccessFileOutputFile = null;
            FileChannel outputFileChannel = null;
            try {
                // Create a random access file with 'rw' permission..
                randomAccessFileOutputFile = new RandomAccessFile(FILER_LOCATION + File.separator + "readme.txt", "rw");
                outputFileChannel = randomAccessFileOutputFile.getChannel();
                //Read line of code one by one and converted it into byte array to write into FileChannel.
                final byte[] bytes = (MESSAGE_WRITE_ON_FILER + System.lineSeparator()).getBytes();
                // Defined a new buffer capacity.
                ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
                // Put byte array into butter array.
                buffer.put(bytes);
                // its flip the buffer and set the position to zero for next write operation.
                buffer.flip();
                /**
                 * Writes a sequence of bytes to this channel from the given buffer.
                 */
                outputFileChannel.write(buffer);
                System.out.println("File Write Operation is done!!");

            } catch (IOException ex) {
                System.out.println("Oops Unable to proceed file write Operation due to ->" + ex.getMessage());
            } finally {
                try {
                    outputFileChannel.close();
                    randomAccessFileOutputFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        }

    }
这是必要的
flip()
。(然而,我确实使用了
wrap()
)这是有意义的,现在需要的是
flip()
。(然而,我确实使用了
wrap()
)现在,这是有意义的。。。。或者在从缓冲区写入后执行
buffer.compact()
。。。。或者在从缓冲区写入后执行
buffer.compact()