Text and Binary Files
Binary files
Two ways with binary strings
Two ways to write a binary string
// create a test string
String testString = "This is a test string.\n";
// use the writeUTF method
out.writeUTF(testString);
int writeSize1 = out.size();
System.out.println(
"writeUTF writes " + writeSize1 + " bytes.");
// use the writeChars method
out.writeChars(testString);
int writeSize2 = out.size() - writeSize1;
System.out.println(
"writeChars writes " + writeSize2 + " bytes\n");
out.close();
Output of the code that writes a binary string
writeUTF writes 25 bytes. writeChars writes 46 bytes.
The file opened in a text editor
Two ways to read a binary string
// get total bytes
int totalBytes = in.available();
// use the readUTF method
String string1 = in.readUTF();
int readSize1 = totalBytes - in.available();
System.out.println("readUTF reads " + readSize1 + " bytes.");
// use the readChar method
int readSize2 = 0;
String string2 = "";
for (int i = 0; i < testString.length(); i++)
{
string2 += in.readChar();
readSize2 += 2;
}
System.out.println(
"readChar reads " + readSize2 + " bytes.\n");
Output of the code that reads a binary string
readUTF reads 25 bytes. readChar reads 46 bytes.