Java tutorial #2 Writing to a file with FileOutputStream

in #java8 years ago

So just like in the last tutorial, we will need to create a main method that throws an IOException

Previous tutorial: https://steemit.com/java/@nicetea/java-tutorial-1-reading-a-file-with-fileinputstream

public static void main(String[] args) throws IOException

Next, we will create the actual OutputStream object. NOTE: This time we don't need to create a file "steemit.txt" by ourselves!

OutputStream f = new FileOutputStream("steemit.txt");

Now to the main code:

int content;
        while((content = System.in.read()) != -1)
            if(content == 48)
                break;
            else
                f.write(content);

Again, we are declaring a variable content, which will store the current byte. If the current content should be 48, which is equivalent to a 0, then the programm will exit. So we can type anything inside until we type a 0 and hit enter.

Running the program, entering "Steemit is awesome"+ hit ENTER

Selection_015.png

Program terminates, as we entered a "0"+hit ENTER

Selection_016.png

Confirming the file

Selection_017.png

Stay tuned!

Coin Marketplace

STEEM 0.13
TRX 0.33
JST 0.034
BTC 110797.76
ETH 4320.82
USDT 1.00
SBD 0.83