Java tutorial #2 Writing to a file with FileOutputStream

in java •  8 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!

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!