- Binary files in java
- Binary files in java
- Java: How to write binary files?
- Create a binary file in java
- Binary File Handling in Java
- What is Binary File Handling
- Write primitive data types to a binary file
- Example
- Read primitive data types from a binary file
- Example
- Output
- Write an object to a binary file
- Example
- Output
- Read an object from a binary file
- Example
- Output
Binary files in java
Solution 1: It’s not that «Binary files» can’t be read by text editors, it’s that «binary files containing characters useless to a text editor can’t be read/edited in a meaningful way». Solution 2: Binary files can be opened by most text editors too, it just depends on what the binary values are and how the editor interpret them as text values.
Binary files in java
I Know that binary files connot be read by text editors, thay can be read only by programs. but when I create binary files using java(bytes), I can open files and read it ? why that happens? In other words, I see a plain text rather than a sequence of zeros and ones. I know that in java there are byte-based streams and character-based streams. when I use byte-based streams such as fileoutputstream, the output is characters not bytes.
File file = new File("Myfile.dat"); // .txt or .bin FileOutputStream fos = new FileOutputStream(file); String data = "Hello, world"; fos.write(data.getBytes()); fos.close();
when I open Myfile.dat using notepad, I expect to see special characters or 0s and 1s but I can read the content «hello world». So I do not undrstand how byte-based streams store characters in binary format?
It’s not that «Binary files» can’t be read by text editors, it’s that «binary files containing characters useless to a text editor can’t be read/edited in a meaningful way». After all, all files are binary: it just depends on what’s contained in them.
Binary files can be opened by most text editors too, it just depends on what the binary values are and how the editor interpret them as text values. There is no reason why you couldn’t open the output of your Java program in Notepad or any simple text editor — you’ll just see gibberish and special characters! If you wan to see the contents as binary then you’ll need a binary file editor/viewer such as hexEdit.
What exactly do you mean by «binary file»? There is no magic tag that marks a file as either a «binary file» or a «text file» (at least not in any OS in common use these days).
A file is nothing but a stream of bytes with a name and some metadata (creation date, permissions, . ) attached.
Whether the content can be interpreted as text or bytes depends entirely on the content.
So if you write a file only using binary values less than 128 (and avoid some low values), then the result is valid ASCII and might look (roughly) like a text file when opened in a text editor.
If, however, you write random bytes to a file, then opening it with a text editor will not result in sane output.
Are there any Java Frameworks for binary file parsing?, My problem is, that I want to parse binary files of different types with a generic parser which is implemented in JAVA. Maybe describing the file format with a configuration file which is read by the parser or creating Java classes which parse the files according to some sort of parsing rules.
Java: How to write binary files?
I have been doing web programming for several years now and since then I have not done any programming for desktop applications, and I have forgotten so many things. Please be patient if this is too simple.
Now I have this situation:
I am trying to store some hashed words in a file. I think I should use binary files for this (please correct me if I am wrong). But I have no idea how should I write the words to the file. I tried many ways, but when I read back the file, and try to decrypt the words, I get BadPaddingException .
Does anyone have any IDEA How to write the words to a file?
P.S: I use this code for encrypting/decrypting the words (I got it from another StackOverflow thread, with a few modifications):
public static byte[] encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException < SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(password)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, 20)); return pbeCipher.doFinal(property.getBytes("UTF-8")); >public static String decrypt(byte[] property) throws GeneralSecurityException, IOException
Well, just use FileInputStream and FileOutputStream =)
// encrypted data in array byte[] data = . FileOutputStream fos = . fos.write(data, 0, data.length); fos.flush(); fos.close();
File inputFile = new File(filePath); byte[] data = new byte[inputFile.length()]; FileInputStream fis = new FileInputStream(inputFile); fis.read(data, 0, data.length); fis.close();
Above code assumes that one file holds single encrypted item. If you need to hold more than one item in the single file, you’ll need to devise some format scheme for that. For example, you can store number of bytes in encrypted data as 2 bytes, before data itself. 2 bytes per item means encrypted item can not be longer than 2^16 bytes. Of course, you can use 4 bytes for length.
Saving as a text document would seem to make more sense to me, the data is already a so there’s no need to convert it to a byte[] and if you need to read from the file would be pretty convenient. Unless you’re saving it from the web and its already coming through a socket as a byte[] . I know it says don’t provide your opinion but its strictly a matter of opinion, that was the only part of your question left unanswered by the previous two answered
Create a binary file in java, create a binary file-> Absolutely doesn’t cover the point; Editing a binary file in java-> They are talking about offsets and stuff, when I just need to write the data and stop; Binary files in java-> Vague. And now to the point. I’ve got a file with a specific extension, to be more exact it’s .nbs. I want to create a file …
Create a binary file in java
These are the related questions that might cause my question to be closed, even though I specify another question:
- Java: How to write binary files? -> Doesn’t really cover the point that I am talking about
- create a binary file -> Absolutely doesn’t cover the point
- Editing a binary file in java -> They are talking about offsets and stuff, when I just need to write the data and stop
- binary files in java -> Vague.
And now to the point. I’ve got a file with a specific extension, to be more exact it’s .nbs . I want to create a file and then write the specific data to it.
That might have sounded vague so let me show you the code I have started with.
try < File bpdn = new File(getDataFolder() + "song.nbs"); if (!bpdn.exists()) < bpdn.createNewFile(); >FileOutputStream fos = new FileOutputStream(bpdn); > catch (IOException e)
I’ll provide you even more details. So I’ve got a song.nbs file that I have created in the past, for myself. And now, whenever a person runs my application, I want it so there’s a new song.nbs file with the exact contents of a file that I have on my PC right now. Therefore, I need to somehow get the bytes of my existing song.nbs and then copy and paste them in my Java application. or is it the way? I neither know how to get the bytes of my own file right now, nor do I know how to write them.
You need to create a resources folder. More info here.
Assuming your project structure is
ProjectName/src/main/java/Main.java
you can create a resources folder inside main/ :
ProjectName/src/main/java/Main.java ProjectName/src/main/resources/
Move your song.nbs you want to read inside resources/ :
ProjectName/src/main/java/Main.java ProjectName/src/main/resources/song.nbs
Now, get the InputStream of song.nbs stored there:
final ClassLoader classloader = Thread.currentThread().getContextClassLoader(); final InputStream is = classloader.getResourceAsStream("song.nbs");
Then, write this input stream to your new file:
final File bpdn = new File(getDataFolder() + "song.nbs"); if (!bpdn.exists()) bpdn.createNewFile(); final FileOutputStream os = new FileOutputStream(bpdn); byte[] buffer = new byte[1024]; int read; while ((read = is.read(buffer)) != -1)
I think I came up with a solution, but I am not sure if this is works. I’d appreciate if you would take a look.
try < File bpdn = new File(getDataFolder() + "badpiggiesdrip.nbs"); if (!bpdn.exists()) < bpdn.createNewFile(); >FileOutputStream fos = new FileOutputStream(bpdn); fos.write(new byte[] < Byte.parseByte(Arrays.toString(Base64.getDecoder().decode(Common.myString))) >); > catch (IOException e)
Common.myString is just a string, that contains data of this type:
and it’s encoded in Base64.
Writing byte[] to a File in Java, As with the Java NIO package, we can write our byte[] in one line:. Files.write(dataForWriting, outputFile); Guava’s Files.write method also takes an optional OptionOptions and uses the same defaults as java.nio.Files.write.. There’s a catch here though: The Guava Files.write method is marked with the @Beta …
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.
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) <> > > >