Streams - It is a continuous flow of water but since this is programming, just change water to data. Data can be 1 or 0 or bits that is used by the computer to processed the inputs and the outputs and then display it to the monitor. A 1 represents 5 volts and 0 represents a ground. So, streams is a continuous flow of data.
Input stream - to read data from the source or to get some water.
Output stream - to write data to a destination or to throw those waster water to the stream and the concerned destination will collect those waste water.
byte stream - it uses a 8 bits (or a byte) to program the input and output. Note that byte streams comes from InputStream and OutputStream.
File I/O byte stream
1. FileInputStream - it creates access to the file to read.
2. FileOutputStream - it creates access to write to the file you specified.
=================
class YourByteStreamClass{
public static void main(String[] args) throws IOException{
YourByteStreamClass.writeSomething("MyTempFile.txt");
YourByteStreamClass.readSomething("MyTempFile.txt");
}
private static void writeSomething(String fileName) throws IOException{
try(FileOutputStream outputStream = new FileOutputStream(fileName)){
Scanner scanner = new Scanner(System.in);
String str;
while(scanner.hasNext()){
str = scanner.next();
outputStream.write(str.getBytes(StandardCharsets.UTF_8));
if(str == "999"){
break;
}
}
scanner.close();
}
}
private static void readSomething(String fileName) throws IOException{
try(FileInputStream inputStream = new FileInputStream(fileName)){
Scanner scanner = new Scanner(inputStream);
String str;
while(scanner.hasNext()){
str = scanner.next();
System.out.println(str);
}
scannner.close();
}
}
}
=================
Result:
Hello World.
Death Note.
999
HelloWorld.DeathNote.999
Note:
1. The underlined words is the input that you type in the console to be scanned and write in the file using FileOutputStream. After the underlined words, FileInputStream will allow you to read those words in the file but this is in integer (byte) and so, you need the Scanner class to translate those bytes to words.
2. Always close the stream. So, we use the try with resource (or try with parameters) to automatically close the stream for us. Therefore, we don't need to use finally just to close the stream. And we use throws as an extension to the method in case there is an exception to catch to automatically throw and catch an exception. Therefore, we can get rid of catch.
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...