Бинарный файл java это

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-университет

В общем, это информация для новичков. Когда пошла тема про считывание информации из файла, встал вопрос: если файл содержит буквы, то почему мы считываем из него цифры в виде байтов и чем является все-таки в таком случае байт. О том, что такое байт, уже достаточно хорошо написано здесь. Но, после прочтения, все равно остался вопрос механизма трансформации букв в цифры, пришлось немного поковыряться в интернете. Поэтому написанное ниже можно считать дополнением. Компьютер хранит каждый файл в виде информации состоящей из нулей и единиц в бинарной форме. Каждый файл фактически является набором байтов следующих один за другим. В типовом варианте существует два вида файлов с информацией: текстовый файл и бинарный файл. Текстовый файл содержит типовой человеческий набор читабельных символов, который мы можем открыть в любом текстовом редакторе. Бинарные файлы состоят из символов, которыми мы не привыкли оперировать в обычной жизни, соответственно требуется специальная программа,, способная их прочитать. Текстовые файлы состоят из букв, цифр и других общепринятых символов. Такие файлы имеют расширения .txt, .py, .csv и т.д. Когда мы открываем такой файл, то видим привычный набор символов, образующих слова. Хотя на самом деле это содержание внутри компьютера не хранится в таком виде. Оно хранится в виде битов, то есть 0 или 1. В различных кодировочных таблицах ASCII, UNICODE или какой другой значение каждого символа определено в бинарном виде. Соответственно, если байт может вмещать 256 символов, то каждому символу соответствует своя двоичная кодировка из нулей и единиц (восемь подряд записанных нулей или единиц дают один символ). Таким образом, когда файл открывается, текстовый редактор осуществляет перевод каждого значения ASCII в привычный нам символ и отображает его уже в привычном виде. Например, под номером 65 в бинарном виде кода ASCII идет 1000001, которое отобразится в файле латинской (не кириллица. Кириллица стартует со 192 позиции) буквой «А». То есть в системе ASCII байту со значением 1000001 соответствует значение латинской буквы «А». Каждая линия файла имеет свой знак переноса строки – EOL (End of Line). Часто этим символом (двумя символами) является «\n» (бинарное значение в ASCII: 00001010). Считав такой символ программа интерпретирует его как конец строки и переход на строку ниже. Есть другие подобные «функциональные символы». Бинарные файлы, как и текстовые, хранятся в бинарном виде, но к ним не «прилагается» программа, которая их раскодирует, то есть нет расшифровочной таблицы типа ASCII. В основном содержание таких файлов представляет собой картинки, аудио и видео, которые в свою очередь являются ужатыми версиями других файлов, например самовыполняющихся файлов (.ехе). Такие файлы (бинарные) не читаются человеком в обычном понимании, поэтому попытка открыть их привычными текстовыми редакторами отобразит кучу непонятного мусора. Соответственно для корректного чтения таких файлов выпускаются специальные программы. Бинарные файлы также хранятся в виде набора байтов, но в данном случае изменение хотя бы одного бита может сделать нечитабельным весь файл. Таблицу символов ASCII можно посмотреть здесь. Таким образом, когда мы читаем файл, то в переменную byte считываются по 8 символов (единица или ноль), которые затем могут быть конвертированы какой-либо программой типа Блокнот в читабельные символы. Источник, который помог разобраться.

Источник

File management

Dealing with text files can be a good option in many situations, when we want to store some simple data, or retrieve it from an existing file. However, sometimes information is not stored in text mode, and we may need to access it. This is the case of many file types in our day to day life, such as audio files or images. In these files, information is stored as a sequence of bytes, and we can’t just open them and read them with text editors.

Regarding binary files, Java provides two base, abstract classes called InputStream and OutputStream , which provide some simple methods to read and write bytes (or groups of bytes) from/to these files. In this document we will see some easy steps to manage these classes and their subtypes, and do some simple operations.

1. Reading from binary files

FileInputStream class provides a read method to read a binary file byte by byte. It returns -1 when the end of file has been reached.

try(FileInputStream fIn = new FileInputStream("file.jpg"))  int data; while ((data = fIn.read()) != -1)  System.out.println(data); > > catch(IOException ex)  System.err.println("Error reading file: " + ex.getMessage()); > 

The class also has another overloaded version of this method to read a bunch of bytes and store it in an array.

 byte[] data = new byte[100]: try(FileInputStream fIn = new FileInputStream("file.jpg"))  int size = 0; while ((size = fIn.read(data)) != -1)  . > > catch(IOException ex)  System.err.println("Error reading file: " + ex.getMessage()); > 

In this last case, read method returns the total number of bytes read, or -1 if the end of file has been reached. Data read will be stored in the byte array that we pass as parameter.

2. Writing to binary files

FileOutputStream class has a write method to write a byte to a binary file.

try(FileOutputStream fOut = new FileOutputStream("file.dat"))  fOut.write(23); fOut.write(44); > catch(IOException ex)  System.err.println("Error writing file: " + ex.getMessage()); > 

It also has an overloaded version of this method to write an array of bytes to the file.

 byte[] data = new byte[100]; // . Fill array with data try(FileOutputStream fOut = new FileOutputStream("file.dat"))  fOut.write(data); > catch(IOException ex)  System.err.println("Error writing file: " + ex.getMessage()); > 

3. Some advanced operations with binary files

Dealing with single bytes in a binary file is not a usual operation. However, sometimes we may need to access a concrete byte or group of bytes in a binary file to check their value, or modify it. But, instead of going byte by byte throughout the file until we reach the desired position, we can make use of random access files.

RandomAccessFile class lets us open a read and/or write stream over a binary file, so that we can move to a given position and read/change the information stored in this file. To do this, we can make use of some useful methods, such as:

  • read , readInt , readFloat … to read information in a given basic type
  • write , writeInt , writeFloat … to write information from a given basic type
  • seek(bytes) or skipBytes(int) to go to a given position in the binary file

For instance, we can check if a PNG file is valid by checking the starting sequence of bytes: 137, 80, 78, 71, 13, 10, 26 and 10​. This little piece of code checks this:

final int[] VALID_HEADER = 137, 80, 78, 71, 13, 10, 26, 10>; try (RandomAccessFile raf = new RandomAccessFile("image.png", "rw"))  int[] headerBytes = new int[VALID_HEADER.length]; for (int i = 0; i  VALID_HEADER.length; i++)  headerBytes[i] = raf.read(); > boolean ok = true; for (int i = 0; i  VALID_HEADER.length; i++)  if (headerBytes[i] != VALID_HEADER[i]) ok = false; > if (ok)  System.out.println("Valid PNG"); > else  System.out.println("Not valid PNG"); > > catch (IOException e)  System.err.println("Error processing image"); > 

We could also modify the value of any of these bytes so that PNG turns into a not valid image, and could not be opened by an image editor:

  • Make sure that BMP is a valid file by checking the first two bytes. They must correspond to letters B and M.
  • Determine the width and height of the BMP file by checking the integers stored at bytes 18-21 (width) and 22-25 (height).

Источник

Binary File Handling in Java

In this lesson, we will learn how to handle binary file in Java.

What is Binary File Handling

Binary File Handling is a process in which we create a file and store data in its original format. It means that if we stored an integer value in a binary file, the value will be treated as an integer rather than text.

Binary files are mainly used for storing records just as we store records in a database. It makes it easier to access or modify the records easily.

We will use the following classes given below to handle data in a binary file.

  • FileOutputStream : used for writing streams of raw bytes to a binary file
  • DataOutputStream : used for writing primitive data types to an output stream.
  • FileInputStream : used for reading streams of raw bytes from a binary file.
  • DataInputStream : used for reading primitive data types from an input stream.

A stream in Java means follow of bytes from one source to another.

video-poster

Write primitive data types to a binary file

The program below demonstrates how to write primitive data types in a binary file using the FileOutputStream and DataOutputStream classes.

Example

import java.io.*; public class Example < public static void main(String args[]) < boolean bo = true; byte byt = 12; char ch = 'A'; short sh = 256; int it = 5862; long lg = 458671; float ft = 78.214f; double db = 2458.325; String str = "Hello Java"; // create a File object File f=new File("d:/delta.txt"); // declare a FileOutputStream object FileOutputStream fos=null; // declare a DataOutputStream object DataOutputStream dos=null; try < // initialize the FileOutputStream object by passing the File object fos=new FileOutputStream(f); // initialize the DataOutputStream object by passing the FileOutputStream object dos=new DataOutputStream(fos); // write primitive data types to a binary file using // the various method of DataOutputStream class dos.writeBoolean(bo); dos.writeByte(byt); dos.writeChar(ch); dos.writeShort(sh); dos.writeInt(it); dos.writeLong(lg); dos.writeFloat(ft); dos.writeDouble(db); // to write string use writeUTF(string) method of DataOutputStream dos.writeUTF(str); >catch(IOException e) < System.out.println(e.getMessage()); >finally < try < // close the file fos.close(); dos.close(); >catch(IOException e) <> > > >

Read primitive data types from a binary file

The program below demonstrates how we can read primitive data types from a binary file using the FileInputStream and DataInputStream classes. We have to read data in the same order we have written it in the file.

Example

import java.io.*; public class Example < public static void main(String args[]) < boolean bo; byte byt; char ch; short sh; int it; long lg; float ft; double db; String str; // create a File object File f=new File("d:/delta.txt"); // declare a FileInputStream object FileInputStream fis=null; // declare a DataInputStream object DataInputStream dis=null; try < // initialize the FileInputStream object by passing the File object fis=new FileInputStream(f); // initialize the DataInputStream object by passing the FileInputStream object dis=new DataInputStream(fis); // read primitive data types from a binary file using // the various method of DataInputStream class bo=dis.readBoolean(); byt=dis.readByte(); ch=dis.readChar(); sh=dis.readShort(); it=dis.readInt(); lg=dis.readLong(); ft=dis.readFloat(); db=dis.readDouble(); // to read string use readUTF(string) method of DataOutputStream str=dis.readUTF(); System.out.println("Boolean data = " + bo); System.out.println("Byte data = " + byt); System.out.println("Char data = " + ch); System.out.println("Short value = " + sh); System.out.println("Int data = " + it); System.out.println("Long data = " + lg); System.out.println("Float data = " + ft); System.out.println("Double data = " + db); System.out.println("String data = " + str); >catch(IOException e) < System.out.println(e.getMessage()); >finally < try < // close the file fis.close(); dis.close(); >catch(IOException e) <> > > >

Output

Boolean data = true Byte data = 12 Char data = A Short value = 256 Int data = 5862 Long data = 458671 Float data = 78.214 Double data = 2458.325 String data = Hello Java

Write an object to a binary file

By implementing the Serializable interface to the user-defined class, we can write an object of the user-defined class in a binary file using the FileOutputStream and ObjectOutputStream classes.

Example

import java.io.*; import java.util.Scanner; class Student implements Serializable < public int roll; public String name; Student() < roll=0; name="None"; >Student(int r, String n) < roll=r; name=n; >> public class Example < public static void main(String args[]) < // create a File object File f=new File("d:/delta.txt"); // declare a FileOutputStream object FileOutputStream fos=null; // declare a ObjectOutputStream object ObjectOutputStream oos=null; // create a Scanner class object Scanner sc=new Scanner(System.in); // create a Student class object Student s=new Student(); // store the student information in the object s System.out.print("Roll: "); s.roll=sc.nextInt(); sc.nextLine(); System.out.print("Name: "); s.name=sc.nextLine(); try < // initialize the FileOutputStream object by passing the File object fos=new FileOutputStream(f); // initialize the ObjectOutputStream object by passing the FileOutputStream object oos=new ObjectOutputStream(fos); // write object to the file oos.writeObject(s); System.out.println("Object written to the file"); >catch(IOException e) < System.out.println(e.getMessage()); >finally < try < // close the file fos.close(); oos.close(); >catch(IOException e) <> > > >

Output

Roll: 1 Name: Thomas Object written to the file

Read an object from a binary file

We can read an object of a user-defined class from a binary file using the FileInputStream and ObjectInputStream classes.

Example

import java.io.*; class Student implements Serializable < public int roll; public String name; Student() < roll=0; name="None"; >Student(int r, String n) < roll=r; name=n; >> public class Example < public static void main(String args[]) < // create a File object File f=new File("d:/delta.txt"); // declare a FileInputStream object FileInputStream fis=null; // declare a ObjectInputStream object ObjectInputStream ois=null; // create a Student class object Student s=new Student(); try < // initialize the FileOutputStream object by passing the File object fis=new FileInputStream(f); // initialize the ObjectInputStream object by passing the FileInputStream object ois=new ObjectInputStream(fis); // read object from the file an typecast it by the Student class s=(Student)ois.readObject(); System.out.println("Roll: "+s.roll); System.out.println("Name: "+s.name); >catch(Exception e) < System.out.println(e.getMessage()); >finally < try < // close the file fis.close(); ois.close(); >catch(IOException e) <> > > >

Output

Источник

Читайте также:  Birthday Reminders for August
Оцените статью