Menu
Topics Index
...
`

OutputStreamDemo - Java Example Program


OutputStreamDemo
class OutputStreamDemo
{
    public static void main(String[] args) throws IOException
    {
        File f = new File("E:JavaPrograms\\FolderOne\\fileOne.txt"); // LINE A
        OutputStream os = new FileOutputStream(f); // LINE B
        if(f.exists()) // LINE C
        {
            System.out.println("File exists.");
    
            // LINE D
             byte b[] = {'i',' ','a','m',' ','f','i','l','e','O','n','e','.'};
            // Writing into file fileOne
             os.write(b);
        }
        else
            System.out.println("File not found.");
        os.close(); // LINE F
    
        // Reading from fileOne
        InputStream is = new FileInputStream(f);
        int i = 0;
        while((i = is.read()) != -1)
        {
            System.out.print((char) i);
        }
        is.close();
    }
}
OUTPUT

File exists.
i am fileOne.

DESCRIPTION

At LINE A we have given the path for file w.
At LINE B we have created an FileOutputStream object and passed file f as parameter.
At LINE C we are checking whether file f exists or not.
At LINE D we have created a byte array.
At LINE E we are writing byte array b in to fileOne using FileOutputStream object.
At LINE F we are closing the OutputStream.

THINGS TO TRY
  • Write a single character in to fileOne using write(int i) method. See that earlier data in fileOne is erased.

© meritcampus 2019

All Rights Reserved.

Open In App