BinaryWriter
In this chapter you will learn:
Get to know BinaryWriter
The following list has the Commonly Used Output Methods Defined by BinaryWriter
.
void Write(sbyte val)
void Write(byte val)
void Write(byte[ ] buf)
void Write(short val)
void Write(ushort val)
void Write(int val)
void Write(uint val)
void Write(long val)
void Write(ulong val)
void Write(float val)
void Write(double val)
void Write(char val)
void Write(char[ ] buf)
void Write(string val)
Write data with BinaryWriter
using System; /* j a va2 s . c o m*/
using System.IO;
class MainClass {
public static void Main() {
BinaryWriter dataOut;
BinaryReader dataIn;
int i = 10;
double d = 1.56;
bool b = true;
try {
dataOut = new BinaryWriter(new FileStream("testdata", FileMode.Create));
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "\nCannot open file.");
return;
}
try {
dataOut.Write(i);
dataOut.Write(d);
dataOut.Write(b);
dataOut.Write(12.2 * 7.4);
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "\nWrite error.");
}
dataOut.Close();
try {
dataIn = new BinaryReader(new FileStream("testdata", FileMode.Open));
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message + "\nCannot open file.");
return;
}
try {
i = dataIn.ReadInt32();
Console.WriteLine("Reading " + i);
d = dataIn.ReadDouble();
Console.WriteLine("Reading " + d);
b = dataIn.ReadBoolean();
Console.WriteLine("Reading " + b);
d = dataIn.ReadDouble();
Console.WriteLine("Reading " + d);
}
catch(IOException exc) {
Console.WriteLine(exc.Message + "Read error.");
}
dataIn.Close();
}
}
Move internal position for a BinaryWriter
using System;//j ava2s. c o m
using System.IO;
public class MainClass
{
public static int Main(string[] args)
{
FileStream myFStream = new FileStream("temp.dat", FileMode.OpenOrCreate,FileAccess.ReadWrite);
BinaryWriter binWrit = new BinaryWriter(myFStream);
binWrit.Write("Hello as binary info...");
int myInt = 9;
float myFloat = 9.8F;
bool myBool = false;
char[] myCharArray = {'H', 'e', 'l', 'l', 'o'};
binWrit.Write(myInt);
binWrit.Write(myFloat);
binWrit.Write(myBool);
binWrit.Write(myCharArray);
binWrit.BaseStream.Position = 0;
Console.WriteLine("Reading binary data...");
BinaryReader binRead = new BinaryReader(myFStream);
int temp = 0;
while(binRead.PeekChar() != -1)
{
Console.Write(binRead.ReadByte());
temp = temp + 1;
if(temp == 5)
{
temp = 0;
Console.WriteLine();
}
}
binWrit.Close();
binRead.Close();
myFStream.Close();
return 0;
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Create new file with write permission and not sharing
- Creates a file with read-write access that allows others to read
- Create FileStream from FileInfo for writing
- Create FileStream from FileInfo for reading