Java : read and write to a binary file
Code for reading a binary file :
Code for writing to a binary file :
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 :
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Comments
Post a Comment