In this post we’ll write following programs -
- Program 1 to Write BOOLEAN data type in file using DataOutputStream
- Program 2 to Read BOOLEAN from file using DataInputStream - java file IO
Program 1 to Write BOOLEAN data type in file using DataOutputStream >
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class WriteBooleanToFileUsingDataOutputStream {
public static void main(String... args) {
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
// create FileOutputStream for writing in file
fos = new FileOutputStream("c:/myFile.txt");
dos = new DataOutputStream(fos);
boolean booleanToBeWrittenInFile = true;
// write boolean data type in file using writeBoolean(boolean) method
dos.writeBoolean(booleanToBeWrittenInFile);
System.out.println("boolean data type to be written in file = "
+ booleanToBeWrittenInFile);
System.out.println("boolean data type has been written in file");
dos.flush(); // bytes in buffer are written in file
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dos != null){
dos.close(); //close DataOutputStream
}
if (fos != null){
fos.close(); //close FileOutputStream
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* OUTPUT
boolean data type to be written in file = true
boolean data type has been written in file
*/
|
Program 2 to Read BOOLEAN from file using DataInputStream - java file IO >
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class ReadBooleanFromFileUsingDataInputStream {
public static void main(String... args) {
FileInputStream fis = null;
DataInputStream dis = null;
try {
// create FileInputStream for reading from file
fis = new FileInputStream("c:/myFile.txt");
dis = new DataInputStream(fis);
while (dis.available() > 0) {
// read boolean data type from file using readBoolean() method.
boolean booleanReadFromFile = dis.readBoolean();
System.out.print("boolean data type read from file = "
+ booleanReadFromFile);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null){
dis.close(); //close DataInputStream
}
if (fis != null){
fis.close(); //close FileInputStream
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/* OUTPUT
boolean data type read from file = true
*/
|
RELATED LINKS>
Copy a file in java 2 in ways
Program to Create Directory - Single and multiple (i.e. parent and child directories) in java file IO
Program to Identify File or Directory - in java file IO | And in java 7 using java.nio.file
Difference between Stream (FileInputStream) and Reader (FileReader) in java file handling
Program to Read text from file using FileInputStream and Try with resource provided in java 7
Labels:
Core Java
File IO/File handling