Google+

269. Using FileOutputStream I/O Class









FileOutputStream is used to write text into any file using the bytes values instead of characters as shown in the below example -

Example -

File file1 = new File("abc.txt");

FileOutputStream fos = new FileOutputStream(file1);

byte b[] = {65, 66, 67, 68, 69, 70};   //Providing byte values instead of characters for writing

fos.write(b);

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a new Java Class 'FileOutputStreamDemo.java' with main( ) method in the existing Java Project 'Project 51' as shown below -


2. Create a File Class object for 'abc.txt' file in our project workspace as shown below (Resolve import error) -



3. Create a FileOutputStream I/O Class object for the above file file1 as shown below -



4. Resolve the error by selecting 'Adding throws declaration' from the error message as shown below (I am adding throws for explanation purpose, please use try catch instead) -



5. Observe that throws with FileNotFoundException Class got added to the method declaration and the error got resolved as shown below -



6. Create a byte array say b[] and assign the byte values 65,66,67,68,69 & 70 to the byte array as shown below -


7. Pass the byte array variable 'b' to the write( ) method of FileOutputStream Class as shown below (write( ) method will take byte values as input from byte array variable 'b' and convert the values to characters automatically and write the converted characters to the specified text file 'abc.txt' ) -


8. Resolve the error by selecting 'Add throws declaration' option from the error message as shown below -


9. Observe that the throws statement with IOException Class got added to the method declaration and the error got resolved as shown below -


10. Close the FileOutputStream object fos to resolve the warning messages as shown below -



11. Save & Run the program and observe the byte values got converted to ABCDEF and written into the file 'abc.txt' file by the write( ) method as shown below -



Hence we have used write( ) method of FileOutputStream I/O Class to write text into a file using the entered byte values.






Please comment below to feedback or ask questions.

Reducing the object creation statements will be explained in the next post.





No comments: