Java : read and write to a binary file

Code for reading a binary file :

Path path = Paths.get("myFile.bin");
if(Files.exists(path)){
File file = path.toFile();
try(DataInputStream in = new DataInputStream(
new BufferedInputStream(
new FileInputStream(file)))){
while(in.available() > 0){
System.out.print(in.readUTF());
}
}catch(IOException e){
//do something with exception
}
}


Code for writing to a binary file :

Path path = Paths.get("myFile.bin");
if(Files.exists(path)){
File file = path.toFile();
try(DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(file)))){
out.writeUTF("This is a string to record");
}catch(IOException e){
//do something with exception
}
}
As said in a previous article, you should use buffered stream for improving I/O operations. It's also considered a best practice to use the try-with-resources for releasing resources.

Comments

Popular posts from this blog

Spring JPA : Using Specification with Projection

Chip input using Reactive Form