It is a common practice to read file contents to display contents on the screen in the form of text. But, the ordinary output stream has no method to write contents to STDOUT or STDERR. It is the task of the FileOutputStream class to write the data to STDOUT or STDERR.
FileOutputStream is a class in the java.io package that can be used to output a stream of bytes to a specified file. The method of its use is simple: you create a FileOutputStream object and then call its writeUTF() method. This method takes a character or byte array and creates a stream that can write to the file, or, more specifically, to the system’s default output stream.
In this article, you will learn how to use the FileOutputStream class to write text to a file.
FileOutputStream in Java is a special subclass of OutputStream that provides methods to write data to a file or a FileDescriptor. Simply put, a file output stream is an OutputStream that writes data to a file. It stores the data as individual bytes. The output stream of a file can be used to create a text file. If you z. For example, if you want to write character strings to a text file, you use the FileOutputStream object. The FileOutputStream class allows us to write byte- and character-oriented data. However, for character-oriented data, it is recommended to use FileWriter and not FileOutputStream. FileOutputStream was added in Java version 1.0. It is available in the java.io.FileOutputStream package.
Explanation of class FileOutputStream in Java
The class FileOutputStream is derived from the class OutputStream. The class outputStream is an abstract superclass of all classes that represent an output stream of bytes, such as. B. FileOutputStream, ObjectOutputStream, etc. The Java FileOutputStream class implements the Closeable, Flushable, and AutoCloseable interfaces. The general declaration of the java.io.FileOutputStream class in java looks like this: public class FileOutputStream extends OutputStream implements Closeable, Flushable, AutoCloseable
Constructor of the class FileOutputStream
The FileOutputStream class defines the following constructors to create a FileOutputStream instance. They are as follows: 1. FileOutputStream(File File) : This constructor creates a file output stream to write data to the specified File object. The contents of each existing file will be overwritten. 2. FileOutputStream(File, boolean append) : This constructor creates a file output stream to write data to the specified File object. If append is true, the data is added to the existing file with the following existing content. If add is false, the existing data in the file is deleted when the output file stream is established. 3. FileOutputStream(FileDescriptor fdObj) : This constructor creates an output stream to write data to the specified file descriptor. 4. FileOutputStream(String filename) : This form of constructor creates an output stream to write to the file with the specified name. 5. FileOutputStream(String name, boolean append) : This constructor creates an output stream to write to the file with the specified name. If append is true, the data is added to the file with the next available content. If append is false, the contents of the existing file are overwritten. In all the above cases, if the file cannot be opened for writing for any reason, an exception called FileNotFoundException is thrown.
How to create a file with FileOutputStream?
Follow the steps below to create a text file to store certain characters or text. These include: 1. First we need to read the data from the keyboard. To do this, we need to add the keyboard to the Inputstream class. The syntax for reading data from the keyboard is given below: DataInputStream dis = new DataInputStream(System.in) ; In the above declaration, System.in represents a keyboard associated with a DataInputStream object whose reference variable is dis. 2. Second: Adds the file in which the data is to be stored to the output stream. Here is the syntax to add the fileout.txt file to the FileOutputStream : FileOutputStream fos = new FileOutputStream(fileout.txt) ; Here for represents an object reference variable of the FileOutputStream class. 3. The third step is to read the data from the DataInputStream and write it to the FileOutputStream. This means that we will read the data from the dis object and write it to the fos object. The syntax is as follows: ch = (char)dis.read() ; fos.write(ch) ; Finally, the file must be closed after any input or output operations have been performed on it. Otherwise, the data in the file may be corrupted. Refer to the following figure to understand these steps.
Methods of the class FileOutputStream in Java
The FileOutputStream class does not define any new methods. Since the class FileOutputStream is derived from the class OutputStream, all methods of this class are inherited from OutputStream. The most commonly used methods are as follows: 1. void close() : This method is used to close the output stream of the file and free up all system resources associated with that stream. 2. void protected finalize() : This method removes the connection to the output stream of the file. 3. FileChannel getChannel() : This method returns a unique FileChannel object associated with the output stream of the file. 4. FileDescriptor getFD() : It returns the file descriptor associated with the thread. 5. void write(int b) : This method writes the specified value or byte to the output stream of this file. 6. void write(byte[ ] b) : It writes a full set of bytes to the output file stream. 7. void write(byte[ ] b, int off, int numBytes) : This method writes the number of bytes of the specified byte array, starting with an offset, to the output file stream. void flush( ) : This method clears the output stream and forces the writing of all buffered output bytes. All these methods throw an exception called IOException when an IO error occurs. So you have to declare that you throw an exception java.io.IOException in a method or put some code in the try-catch block.
Example program based on Java FileOutputStream
1. Let’s look at an example program where we want to write a byte to a file. Program source code 1 : package javaProgram; import java.io.FileOutputStream; public class FileOutputStreample { public static void main(String[] args) { try { String filepath = D:_fileout.txt ; FileOutputStream fos = new FileOutputStream(filepath);fos.write(87);fos.close();System.out.println(Successfully written);}catch(FileNotFoundException e){System.out.println(e);}} Exit: Successfully written The W data was successfully written to the text file fileout.txt. 2. Let’s look at another example of a program that writes a string to a text file. Check the source code. Program source code 2 : package javaProgram; import java.io.FileOutputStream; public class FileOutputStreample { public static void main(String[] args) { try { String filepath = D:\fileout.txt; FileOutputStream fos = new FileOutputStream(filepath); String str = Welcome to , Shivam complex, Dhanbad ; byte bytearray[] = str.getBytes();fos.write(bytearray);fos.close();System.out.println(Success written);}catch(Exception e){System.out.println(e);}} Exit: Successfully written Welcome to , Shivam complex, Dhanbad data has been successfully saved to the text file fileout.txt. 3. Let’s look at an example program where we figure out how to read data from the keyboard and write it to the fileout.txt. To understand it better, take a look at the source code of the program. Program source code 3 : package javaProgram ; import java.io.DataInputStream ; import java.io.FileOutputStream ; public class FileOutputStreample { public static void main(String[] args) { try { DataInputStream dis = new DataInputStream(System.in) ; String filepath = D:_myfileout.txt ; FileOutputStream fos = new FileOutputStream(filepath); System.out.println(Enter text (@ the end)) ; int value = 0 ; while((value = dis.read()) != ‘@’){ char ch = (char)value; fos.write(ch); } fos.close(); System.out.println(Writing passed…); }catch(Exception e){ System.out.println(e); } } } Exit: Enter text Welcome to , Dhanbad Best online portal to become a Java coding expert @ Successfully written… Welcome to , Dhanbad, Best Online Portal to become expert in Java coding data has been successfully written to the myfileout text file. In this example program, we read the data from the keyboard and write it to the file myfileout.txt. This program accepts data from the keyboard as long as the user types @ to complete the statement. You can see the output, we typed two lines of instruction and typed @ to complete the instruction. Now open the file myfileout.txt and see if the data was successfully written to the file or not. When the above program is run again, you will notice that the data in the old file myfileout.txt is completely lost and new data is stored in the file when the text is written. View the result of the second program run. Exit: Enter text (@ at end) Industrial programming in Java by @ Successful writing… Note that the previous two lines of assertions have been removed from the file and the file has been created as a new file. The new file myfileout.txt now contains only the third line that was entered when the code was last run. If you don’t want to lose the data from the previous file and just add the new data to the end of the existing data, open the file by writing true with the file name. The syntax is as follows: FileOutputStream fos = new FileOutputStream(filepath, true) ; If you use this operator in a previous program and run the program multiple times, all previous data is saved and the new data is appended to the old.
How do I copy data from one file to another?
Let’s create a program to copy data from one file to another using the classes FileInputStream and FileOutputStream. In the first file, myfile.txt, we will enter the data as Welcome to . Then we copy it and save it in the second file myfileout.txt. Take a look at the source code to understand it better. Program source code 4 : package javaProgram ; import java.io.FileInputStream ; import java.io.FileOutputStream; public class CopyData { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream(D:\file.txt); FileOutputStream fos = new FileOutputStream(D:\fileout.txt) ; int i = 0; while ((i = fis.read()) != -1){ char ch = (char)i; fos.write(ch); } fis.close(); System.out.println(Written successfully…); }catch(Exception e) { System.out.println(e); } } } Exit: Successfully written… The data in myfile.txt is copied to fileout.txt. Now open the fileout.txt file and check if the data was copied successfully or not. I hope this tutorial has covered all the important points of the FileOutputStream class in Java with example programs. I hope you understand and practice all the programs. Thanks for reading!!!FileOutputStream is a Java class that reads and writes data to and from a file. It is a part of the java.io package and is also a part of the java.io.File class. FileOutputStream is a type of a stream. A stream is a computer data structure that facilitates the transmission of information between applications. A stream is a series of data packets that is buffered and transmitted as a unit.. Read more about fileinputstream and fileoutputstream in java and let us know what you think.
Frequently Asked Questions
What is FileOutputStream in Java?
FileOutputStream is a special InputStream that takes a byte array and outputs that byte array through a FileOutputStream. The method of the FileOutputStream is to write the byte array to a particular file in a particular folder. This is achieved by way of a WriteTo method. In the case of writing to a file, the byte array is written to the file on disk. In the case of writing to a file, the byte array is written to the file in memory. In both cases, the array contents are written as binary data, as opposed to the character data of a string in a StringOutputStream. FileOutputStream in JAVA is a class which serves as an output stream for data that is being output from a java program. When used in an application program you might write the following code: FileOutputStream fos = new FileOutputStream(“output.txt”); fos.write(“we’ll write in file”);
How do I use FileOutputStream in Java?
In Java, we use FileOutputStream class for writing particular output data to a given file. The FileOutputStream class is an abstract class. It provides methods for writing data. It is used to write data to a file or other output stream. It is an abstract class. If you’ve ever needed to work with some kind of stream in Java, then you’ll have come across FileOutputStream. This class allows you to output a file to a file, and works with many types of files, including text, images, binary, and audio.
Why is FileOutputStream used?
FileOutputStream is a mysterious class that within a few weeks of it’s introduction to the Java world, has become the most complained about Java class. It has been the source of numerous Stack Overflow questions (some of which are still unanswered), and damaged the reputation of the class. I won’t bore you with the history of this class – you can read about it here . FileOutputStream is a class used to write data to a file. It is in the java.io package. Here is a short example of its usage:
Related Tags:
fileoutputstream in java examplefileoutputstream constructor in javafileoutputstream in java – geeksforgeeksfileoutputstream to byte arrayfileoutputstream in java 8fileoutputstream class is used to write,People also search for,Feedback,Privacy settings,How Search works,fileoutputstream in java example,fileoutputstream constructor in java,fileoutputstream in java – geeksforgeeks,fileinputstream and fileoutputstream in java,fileoutputstream to byte array,import java.io.fileoutputstream public class fileoutputstream example,fileoutputstream in java 8,fileoutputstream class is used to write