- Java — Как сохранить байт[]в файл
- Рекомендации
- Writing Byte[] to a File in Java
- Write Byte to File in Java
- Using FileOutputStream to Write Byte to File in Java
- Using java.nio.file to Write Byte to File
- Using Apache Commons IO Library to Write Byte to File in Java
- Related Article — Java Byte
- Related Article — Java File
- Java Program to Write Bytes using ByteStream
Java — Как сохранить байт[]в файл
В этом примере Java показано, как прочитать файл в байтовый массив и сохранить байтовый массив обратно в новый файл с помощью классических try-catch-try-catch, JDK 7 try-resources и решения Java.NIO.
package com.example; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class ArrayOfBytesToFile < private static final String UPLOAD_FOLDER = "C:\\temp\\"; public static void main(String[] args) < FileInputStream fileInputStream = null; try < File file = new File("C:\\temp\\testing1.txt"); byte[] bFile = new byte[(int) file.length()]; //read file into bytes[] fileInputStream = new FileInputStream(file); fileInputStream.read(bFile); //save bytes[] into a file writeBytesToFile(bFile, UPLOAD_FOLDER + "test1.txt"); writeBytesToFileClassic(bFile, UPLOAD_FOLDER + "test2.txt"); writeBytesToFileNio(bFile, UPLOAD_FOLDER + "test3.txt"); System.out.println("Done"); >catch (IOException e) < e.printStackTrace(); >finally < if (fileInputStream != null) < try < fileInputStream.close(); >catch (IOException e) < e.printStackTrace(); >> > > //Classic, < JDK7 private static void writeBytesToFileClassic(byte[] bFile, String fileDest) < FileOutputStream fileOuputStream = null; try < fileOuputStream = new FileOutputStream(fileDest); fileOuputStream.write(bFile); >catch (IOException e) < e.printStackTrace(); >finally < if (fileOuputStream != null) < try < fileOuputStream.close(); >catch (IOException e) < e.printStackTrace(); >> > > //Since JDK 7 - try resources private static void writeBytesToFile(byte[] bFile, String fileDest) < try (FileOutputStream fileOuputStream = new FileOutputStream(fileDest)) < fileOuputStream.write(bFile); >catch (IOException e) < e.printStackTrace(); >> //Since JDK 7, NIO private static void writeBytesToFileNio(byte[] bFile, String fileDest) < try < Path path = Paths.get(fileDest); Files.write(path, bFile); >catch (IOException e) < e.printStackTrace(); >> >
Рекомендации
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.
Write Byte to File in Java
- Using FileOutputStream to Write Byte to File in Java
- Using java.nio.file to Write Byte to File
- 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
Java Program to Write Bytes using ByteStream
Java Byte streams are used to perform input and output of 8-bit bytes. To write Bytes using BytesStream to a file Java provides a specialized stream for writing files in the file system known as FileOutputStream. This stream provides the basic OutputStream functionality applied for writing the contents of a file.
FileOutputStream class is an output stream for writing data to a file. It is a class that belongs to byte streams.The FileOutputStream class extends the OutputStream abstract class.So it inherits all the standard OutputStream functionality for writing to a file.FileOutputStream provides only a low-level interface to writing data. You can create a FileOutputStream from a String pathname or a File object.The FileOutputStream constructors don’t throw a FileNotFoundException. If the specified file doesn’t exist, the FileOutputStream creates the file. The FileOutputStream constructors can throw an IOException if some other I/O error occurs. If the specified file does exist, the FileOutputStream opens it for writing. When you actually call a write() method, the new data overwrites the current contents of the file. To append data to an existing file, use a different constructor that accepts an append flag.
Now, discussing these inbuilt methods in order to understand internal working while dealing with file concepts in java.
Considering them individually, discussing methods for greater understanding.
In order to write into a file, three arises a need to convert the text(content) into an array of bytes before writing it into the file. This method does the role by converting the characters in this String object to an array of byte values. The characters in the string are converted to bytes using the system’s default character encoding scheme.
Parameter: NA
Returns: A byte array that contains the characters of this String
2. write() Method
The write(byte[] b) method of FileOutputStream class is used to write b.length bytes from the specified byte array to this file output stream
public void write(byte[] b) throws IOException ;
Parameters: The data
Returns: This method does not return any value.
3. close() Method
The close() method of FileOutputStream class is used to close the file output stream and releases all system resources associated with this stream.
Parameter: NA
Returns: This method does not return any value.
Implementation:
- Creating an object of the file and passing the local directory path of the file as input.
- Storing random text into String datatype.
- Converting a string into a byte array.
- Write byte data to file output.
- Close the file using theclose() method.