Byte to file class java

Class FileOutputStream

A file output stream is an output stream for writing data to a File or to a FileDescriptor . Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter .

Constructor Summary

Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.

Method Summary

Methods declared in class java.io.OutputStream

Methods declared in class java.lang.Object

Constructor Details

FileOutputStream

Creates a file output stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkWrite method is called with name as its argument. If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

Читайте также:  Динамическое программирование си шарп

FileOutputStream

Creates a file output stream to write to the file with the specified name. If the second argument is true , then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkWrite method is called with name as its argument. If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

FileOutputStream

Creates a file output stream to write to the file represented by the specified File object. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkWrite method is called with the path represented by the file argument as its argument. If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

FileOutputStream

Creates a file output stream to write to the file represented by the specified File object. If the second argument is true , then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection. First, if there is a security manager, its checkWrite method is called with the path represented by the file argument as its argument. If the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason then a FileNotFoundException is thrown.

Читайте также:  Соседние селекторы

FileOutputStream

Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system. First, if there is a security manager, its checkWrite method is called with the file descriptor fdObj argument as its argument. If fdObj is null then a NullPointerException is thrown. This constructor does not throw an exception if fdObj is invalid . However, if the methods are invoked on the resulting stream to attempt I/O on the stream, an IOException is thrown.

Источник

Writing Byte[] to a File in Java

Learn to write the given byte[] into a file using different solutions. We will be using the Java NIO, Commons IO and Guava APIs that provide simple APIs for this usecase.

The Files.write() is the simplest way to write bytes into a file.

We should be very careful about the file open options while writing the bytes. By default, the CREATE , TRUNCATE_EXISTING , and WRITE options are used. It means that the method opens the file for writing, creating the file if it doesn’t exist, or initially truncating the regular file to a size of 0.

byte[] bytes = "testData".getBytes(); Path filePath = Paths.get("test.txt"); Files.write(filePath, bytes);

If we do not overwrite the file content, rather we want to append the bytes into the existing file content then we can use the StandardOpenOption.APPEND option.

byte[] bytes = "testData".getBytes(); Path filePath = Paths.get("test.txt"); Files.write(filePath, bytes, StandardOpenOption.APPEND);

If we want to create a new file, always, then we can pass the option StandardOpenOption.CREATE_NEW . It ensures that the method will throw FileAlreadyExistsException if the file already exists.

byte[] bytes = "testData".getBytes(); Path filePath = Paths.get("test.txt"); Files.write(filePath, bytes, StandardOpenOption.CREATE_NEW);

Using FileOutputStream is another good approach. We can create the output stream for a new or existing file and write the bytes to the stream.

Do not forget to close the output stream if you are not using the try-with-resources statement.

byte[] bytes = "testData".getBytes(); File file = new File("test.txt"); try (FileOutputStream os = new FileOutputStream(file))

The FileUtils class has method writeByteArrayToFile() that writes the byte array data into the specified file. It creates a new file and its parent directories if they do not exist.

File file = new File("test.txt"); byte[] bytes = "testData".getBytes(); FileUtils.writeByteArrayToFile(file, bytes);

Include Commons IO using the latest maven dependency in the project.

Similar to previous solutions, Files.write() method writes the bytes to the specified file. Note that this method overwrites a file with the contents of a byte array.

File file = new File("test.txt"); byte[] bytes = "testData".getBytes(); com.google.common.io.Files.write(bytes, file);

In this short Java tutorial, we learned to write the byte array content into a file using various Java APIs; and Commons IO and Guave libraries.

Источник

Convert Byte Array to File In Java

In this article we are going to present how to convert Byte Array to File using plain Java solutions (also in version JDK7) and libraries like Guava and Apache Commons IO.

2. Save Byte Array in File using FileOutputStream

Let’s start with plain Java solution. To convert byte [] to File we can use FileOutputStream as presented in the following example:

package com.frontbackend.java.io.conversions.frombytearray.tofile; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; public class ByteArrayToFileUsingFileOutputStream < public static void main(String[] args) throws IOException < byte[] bytes = "frontbackend.com".getBytes(StandardCharsets.UTF_8); try (FileOutputStream fos = new FileOutputStream("/tmp/output.txt")) < fos.write(bytes); >> > 

In this example first we create sample byte array, then we open FileOutputStream and write bytes to it using write(. ) method

Note that we are using try-with-resources funcion to automatically close our streams.

4. Convert Byte Array to File using JDK7 Files class

Java 7 comes with many great features and improvements. In the following example code we presented how to convert Byte Array to file using JDK7 s Files` class:

package com.frontbackend.java.io.conversions.frombytearray.tofile; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardCopyOption; public class ByteArrayToFileUsingFiles < public static void main(String[] args) throws IOException < byte[] bytes = "frontbackend.com".getBytes(StandardCharsets.UTF_8); InputStream inputStream = new ByteArrayInputStream(bytes); File file = new File("/tmp/output.txt"); Files.copy(inputStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING); >> 

This example is pretty streightforward, and gives us one-line solution. We used Files.copy(. ) method that convert early prepared ByteArrayInputStream to the file. If the StandardCopyOption.REPLACE_EXISTING is set, the process will replace existing file.

5. Convert Byte Array to File with Guava library

External libraries like Guava comes with great utitlity methods for IO operations and manipulations. In the following example we used Guava to save byte array into a file.

package com.frontbackend.java.io.conversions.frombytearray.tofile; import static com.google.common.io.Files.write; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; public class ByteArrayToFileUsingGuava < public static void main(String[] args) throws IOException < byte[] bytes = "frontbackend.com".getBytes(StandardCharsets.UTF_8); File file = new File("/tmp/output.txt"); write(bytes, file); >> 

In this example we make a use of Files.write(. ) method available with Guava . The method takes byte array and output file as a parameters.

6. Byte Array to File conversion using Apache Commons IO

package com.frontbackend.java.io.conversions.frombytearray.tofile; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; public class ByteArrayToFileUsingFileUtils < public static void main(String[] args) throws IOException < byte[] bytes = "frontbackend.com".getBytes(StandardCharsets.UTF_8); FileUtils.writeByteArrayToFile(new File("/tmp/output.txt"), bytes); >> 

7. Conclusion

In this article, we presented how to convert Byte Array to File in Java. We used plain java solutions and libraries like Guava and Apache Commons IO .

As usual, code examples used in this tutorial are available under our GitHub repository.

Источник

Write Byte to File in Java

Write Byte to File in Java

  1. Using FileOutputStream to Write Byte to File in Java
  2. Using java.nio.file to Write Byte to File
  3. Using Apache Commons IO Library to Write Byte to File in Java

This program demonstrates how to write a byte array to a file in Java. This task can be performed using FileOutputStream and using some libraries mentioned in this article.

Using FileOutputStream to Write Byte to File in Java

The Class FileOutputStream in Java is an output stream used to write data or stream of bytes to a file. The constructor FileOutputStream(File file) creates a file output stream to write to the file represented by the File object file , which we have created in the code below.

The variable s of type String is passed to the getBytes() method, which converts the string into a sequence of bytes and returns an array of bytes. The write() method takes the byte array as an argument and writes b.length bytes from the byte array b to this file output stream.

A file with the extension .txt is created at the given path, and if we open that, we can see the contents same as the string stored in the variable s .

import java.io.File; import java.io.FileOutputStream;  public class ByteToFile   public static void main(String args[])  File file = new File("/Users/john/Desktop/demo.txt");  try   FileOutputStream fout  = new FileOutputStream(file);  String s = "Example of Java program to write Bytes using ByteStream.";  byte b[] = s.getBytes();  fout.write(b);  >catch (Exception e)  e.printStackTrace();  >   > > 

Using java.nio.file to Write Byte to File

Java NIO ( New I/O) package consists of static methods that work on files, directories and it mostly works on Path object. The Path.get() is a static method that converts a sequence of strings or a path string to a Path. It simply calls FileSystems.getDefault().getPath() .

Thus, we can write a byte array b into a file using the Files.write() method by passing the path to the file, and the byte array converted from a string.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths;  public class ByteToFile   public static void main(String args[])  Path p = Paths.get("/Users/john/Desktop/demo.txt");  try   String s = "Write byte array to file using java.nio";  byte b[] = s.getBytes();  Files.write(p, b);  >  catch (IOException ex)   System.err.format("I/O Error when copying file");  >  > > 

Using Apache Commons IO Library to Write Byte to File in Java

The maven dependency for this library is as mentioned below.

   commons-io   commons-io   2.6  

The Apache Commons IO library has the FilesUtils class, it has writeByteArrayToFile() method. This method takes the destination path and the binary data we are writing. If our destination directory or file does not exist, they will be created. If the file exists, it will be truncated before writing.

import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets;  public class ByteToFile   public static void main(String args[])    File file = new File("doc.txt");  byte[] data = "Here, we describe the general principles of photosynthesis".getBytes(StandardCharsets.UTF_8);  try   FileUtils.writeByteArrayToFile(file, data);  System.out.println("Successfully written data to the file");  >  catch (IOException e)   e.printStackTrace();  >  >  > > 
Successfully written data to the file 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Related Article — Java Byte

Related Article — Java File

Copyright © 2023. All right reserved

Источник

Оцените статью