Binary file java example

Reading and Writing Files in Java

One of the most common tasks while creating a software application is to read and write data to a file. The data could be stored in a JSON file, a CSV file, a binary file, or in a text file.

In this article, you’ll learn how to read and write text and binary files in Java. Java provides several APIs (unknown as Java I/O) for reading and writing files right from the beginning. Over the years, these APIs are further improved to provide a simplified and robust interface for dealing with different kinds of files.

If you want to read a simple text file, just use the FileReader class and wrap it in a BufferedReader . Here is an example that uses the BufferedReader class to read a file named input.txt line by line:

try  // create a reader BufferedReader br = new BufferedReader(new FileReader("input.txt")); // read until end of file String line; while ((line = br.readLine()) != null)  System.out.println(line); > // close the reader br.close(); > catch (IOException ex)  ex.printStackTrace(); > 

If you want to read a binary file or a file containing special characters, you need to use the FileInputStream class instead of FileReader . Here is an example:

try  // create a reader FileInputStream fis = new FileInputStream(new File("input.dat")); // read until end of file int ch; while ((ch = fis.read()) != -1)  System.out.print((char) ch); > // close the reader fis.close(); > catch (IOException ex)  ex.printStackTrace(); > 

To write a text file in Java, you should use the FileWriter class and wrap it in a BufferedWriter as shown below:

try  // create a writer BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt")); // write text to file bw.write("Hey, there!"); bw.newLine(); bw.write("See you soon."); // close the writer bw.close(); > catch (IOException ex)  ex.printStackTrace(); > 

You can easily create and write to a binary file in Java by using the FileOutputStream class. Here is an example that creates a new binary file and writes data into it:

try  // create a writer FileOutputStream fos = new FileOutputStream(new File("output.dat")); // write data to file fos.write("Hey, there!".getBytes()); fos.write("\n".getBytes()); fos.write("See you soon.".getBytes()); // close the writer fos.close(); > catch (IOException ex)  ex.printStackTrace(); > 

You might also like.

Источник

Java Read Binary Files

Java Read Binary Files

  1. Read Binary File Using FileInputStream in Java
  2. Read Binary File Using BufferedInputStream in Java
  3. Read Binary File Using InputStreamReader in Java

Reading a binary file can be difficult while trying to open it in software, but we can read Binary files using Java. This tutorial demonstrates different ways of reading binary files in Java.

Read Binary File Using FileInputStream in Java

Using the FileInputStream class in Java, we can easily read the binary files in Java.

package Delfstack;  import java.io.File; import java.io.FileInputStream; import java.io.IOException;  public class Read_Binary   public static void main(String[] args)   try   // create a reader for data file  FileInputStream read = new FileInputStream(new File("input.dat"));   // the variable will be used to read one byte at a time  int byt;  while ((byt = read.read()) != -1)   System.out.print((char) byt);  >   read.close();   > catch (IOException e)   e.printStackTrace();  >  > > 

We created an input.dat binary and then tried to read it through Java.

default: ( %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Test input.dat file from Delftstack %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check = true  check = false ) 

The program above only reads one byte at a time, so that it may take more time for the large binary files.

Read Binary File Using BufferedInputStream in Java

As mentioned above, FileInputStream can only read one byte at a time, which may take more time to read large files. To solve that problem, we use the BufferedInputStream class.

The BufferedInputStream class reads a set of bytes at a time into an array buffer.

package Delfstack;  import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException;  public class Read_Binary   public static void main(String[] args)   try   int Size_Buffer = 16 * 1024; //16kb  // create a reader for data file  FileInputStream read = new FileInputStream(new File("input.dat"));  BufferedInputStream buffered_reader = new BufferedInputStream(read, Size_Buffer);   int byt;  while ((byt = buffered_reader.read()) != -1)   System.out.print((char) byt);  >   buffered_reader.close();   > catch (IOException e)   e.printStackTrace();  >  > > 

The default internal buffer size is 8 kb which can be changed by passing as a parameter to the BufferedInputStream .

default: ( %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Test input.dat file from Delftstack %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check = true  check = false ) 

Read Binary File Using InputStreamReader in Java

The InputStreamReader is used to read binary files with encoding different than our operating system. The encoding of the binary file is passed as a parameter to InputStreamReader .

package Delfstack;  import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets;  public class Read_Binary   public static void main(String[] args)   try   FileInputStream read = new FileInputStream(new File("input.dat"));   // pass the UTF_8 character encoding  InputStreamReader stream_reader = new InputStreamReader(read, StandardCharsets.UTF_8);   int byt;  while ((byt = stream_reader.read()) != -1)   System.out.print((char) byt);  >   stream_reader.close();   > catch (IOException e)   e.printStackTrace();  >  > > 

The code above can read the binary files with a particular encoding. Pass that encoding to the InputStreamReader as a parameter.

default: ( %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Test input.dat file from Delftstack %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check = true  check = false ) 

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

Related Article — Java Binary

Источник

Reading and Writing Binary Files

To open a file for reading, you can use the newInputStream(Path, OpenOption. ) method. This method returns an unbuffered input stream for reading bytes from the file.

Path file = . ; try (InputStream in = Files.newInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) < String line = null; while ((line = reader.readLine()) != null) < System.out.println(line); >> catch (IOException x)

Creating and Writing a File by Using Stream I/O

You can create a file, append to a file, or write to a file by using the newOutputStream(Path, OpenOption. ) method. This method opens or creates a file for writing bytes and returns an unbuffered output stream.

The method takes an optional OpenOption parameter. If no open options are specified, and the file does not exist, a new file is created. If the file exists, it is truncated. This option is equivalent to invoking the method with the CREATE and TRUNCATE_EXISTING options.

The following example opens a log file. If the file does not exist, it is created. If the file exists, it is opened for appending.

import static java.nio.file.StandardOpenOption.*; import java.nio.file.*; import java.io.*; public class LogFileTest < public static void main(String[] args) < // Convert the string to a // byte array. String s = "Hello World! "; byte data[] = s.getBytes(); Path p = Paths.get("./logfile.txt"); try (OutputStream out = new BufferedOutputStream( Files.newOutputStream(p, CREATE, APPEND))) < out.write(data, 0, data.length); >catch (IOException x) < System.err.println(x); >> > 

Reading and Writing Files by Using Channel I/O

While stream I/O reads a character at a time, channel I/O reads a buffer at a time. The ByteChannel interface provides basic read and write functionality. A SeekableByteChannel is a ByteChannel that has the capability to maintain a position in the channel and to change that position. A SeekableByteChannel also supports truncating the file associated with the channel and querying the file for its size.

The capability to move to different points in the file and then read from or write to that location makes random access of a file possible. See the section Random Access Files for more information.

There are two methods for reading and writing channel I/O.

Note: The newByteChannel() methods return an instance of a SeekableByteChannel . With a default file system, you can cast this seekable byte channel to a FileChannel providing access to more advanced features such mapping a region of the file directly into memory for faster access, locking a region of the file so other processes cannot access it, or reading and writing bytes from an absolute position without affecting the channel’s current position.

Both newByteChannel() methods enable you to specify a list of OpenOption options. The same open options used by the newOutputStream() methods are supported, in addition to one more option: READ is required because the SeekableByteChannel supports both reading and writing.

Specifying READ opens the channel for reading. Specifying WRITE or APPEND opens the channel for writing. If none of these options are specified, then the channel is opened for reading.

The following code snippet reads a file and prints it to standard output:

public static void readFile(Path path) throws IOException < // Files.newByteChannel() defaults to StandardOpenOption.READ try (SeekableByteChannel sbc = Files.newByteChannel(path)) < final int BUFFER_CAPACITY = 10; ByteBuffer buf = ByteBuffer.allocate(BUFFER_CAPACITY); // Read the bytes with the proper encoding for this platform. If // you skip this step, you might see foreign or illegible // characters. String encoding = System.getProperty("file.encoding"); while (sbc.read(buf) >0) < buf.flip(); System.out.print(Charset.forName(encoding).decode(buf)); buf.clear(); >> > 

The following example, written for UNIX and other POSIX file systems, creates a log file with a specific set of file permissions. This code creates a log file or appends to the log file if it already exists. The log file is created with read/write permissions for owner and read only permissions for group.

import static java.nio.file.StandardOpenOption.*; import java.nio.*; import java.nio.channels.*; import java.nio.file.*; import java.nio.file.attribute.*; import java.io.*; import java.util.*; public class LogFilePermissionsTest < public static void main(String[] args) < // Create the set of options for appending to the file. Setoptions = new HashSet(); options.add(APPEND); options.add(CREATE); // Create the custom permissions attribute. Set perms = PosixFilePermissions.fromString("rw-r-----"); FileAttribute attr = PosixFilePermissions.asFileAttribute(perms); // Convert the string to a ByteBuffer. String s = "Hello World! "; byte data[] = s.getBytes(); ByteBuffer bb = ByteBuffer.wrap(data); Path file = Paths.get("./permissions.log"); try (SeekableByteChannel sbc = Files.newByteChannel(file, options, attr)) < sbc.write(bb); >catch (IOException x) < System.out.println("Exception thrown: " + x); >> > 

Источник

Читайте также:  Проверка числа на четность php
Оцените статью