Creating a file using FileOutputStream

Creating a file using FileOutputStream

First, we should read data from the keyboard. For read data from keyboard we use DataInputStream  class.

DataInputStream dis = new DataInputStream(System.in);

Now attach a file where the data is to be stored to some output stream. Here, we take the help of FileOutputStream which can send data to the file.

FileOutputStream fout = new¬†FileOutputStream(“file.txt”);

The next step is to read data from DataInputStream and write it into FileOutputStream.

ch=(char)dis.read();
fout.write(ch);

Finally, any file should be closed after performing input or output operation on it, else the data of the file may be corrupted.

Example
class test
{
public static void main(String args []) throws IOException
{
DataInputStream dis = new DataInputStream(System.in);
FileOutputStream fout = new FileOutputStream(“file.txt”);
char ch;
while((ch=(char)dis.read())!=-1);
fout.write(ch);
fout.close();
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *