Data Streams - It is a wrapper for a buffered byte stream. It supports all primitive types and the strings but not the BigDecimal which is used for precise computation. Data streams implements either DataInput interface or DataOutput interface. And the DataInputStream and DataOutputStream respectively used these interfaces.
=================
class PracticingDataStream{
public static void main(String[] args) throws IOException{
String yourFileName = "TemporaryDataStreamFileName.txt";
System.out.println("Enter something below:");
writeSomething(yourFileName);
System.out.println(readSomething(yourFileName));
}
private static void writeSomething(String fileName) throws IOException {
try(FileOutputStream outputStream = new FileOutputStream(fileName);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutput);
Scanner scanner = new Scanner(System.in)
){
String gatherItHere = "";
while(scanner.hasNext()){
String message = scanner.nextLine();
String addingNewLine = message.concat("
");
gatherItHere = gatherItHere.concat(addingNewLine);
if(message.equals("999")){
break;
}
}
dataOutputStream.writeUTF(gatherItHere);
daaOutputStream.flush();
}
}
private static String readSomething(String fileName) throws IOException{
try(FileInputStream inputStream = new FileInputStream(fileName);
BufferedInputStream bufferedInput = new BufferedInputStream(inputStream);
DataInputStream dataInputStream = new DataInputStream(bufferedInput);
Scanner scanner = new Scanner(dataInputStream);
){
String gatherItHere = "";
while(scanner.hasNext()){
String message = scanner.nextLine();
String addingNewLine = message.concat("
");
gatherItHere = gatherItHere.concat(addingNewLine);
}
return gatherItHere;
}
}
}
=================
Result:
Enter something below:
hello
world
999
00hello
world
999
Note:
1. In the readSomething() method, I put the dataInputStream object inside the Scanner class as argument since instead of using the dataInputStream object only. This is because if I did not use a Scanner, after the dataInputStream read from the file, it will throw an EOFException. EOFException is an End Of File Exception.
2. There is a two zero in front of the hello since I have already tried to run it twice and every time it overwrites the previous text message, it does left a delimiter as an indicator that there was a previous message before.
YOU ARE READING
Java Programming
Randomhttps://docs.oracle.com/javase/tutorial/ This is the link where I learned my java lessons online. I choose java as first programming language. I am a career shifter. I just want to start something new. I choose to write it here in Wattpad so that I...