Google+

266. Writing text to a file using write( ) method of FileWriter I/O Class








Using write( ) method of FileWriter I/O Class, we can write the text into the given text file.

write( ) method can directly write our text into the given text file as shown in the below example -

Example -

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

FileWriter fw = new FileWriter(file1);

fw.write("How are you doing today?");

Output -

How are you doing today ?

Lets implement this on Eclipse IDE -

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




2. Go to our Project Workspace, create an empty text file 'abc.txt' as shown below -



3. In Eclipse IDE -> 'FileWriterDemo.java' Class, create a File Class object for the created file 'abc.txt' as shown below (Resolve import error) -




4. Create a FileWriter Class object for the above created file file1 as shown below (Resolve import error) -




5. View the error and select 'Add throws declarations' option from the error message as shown below (I am adding throws for explanation purpose, in reality we should add try/catch to resolve the error)  -



6. Observe that IOException Class got added to the method declaration and our error got resolved as shown below -


7. Now use write( ) method of FileWriter Class, to write the given String text to the specified file 'abc.txt' as shown below -



8. Close the object of  FileWriter Class and observe that the above warning message got resolved as shown below -



9. Save & Run the Java Class 'FileWriter.java' , go to the 'abc.txt' in our project location and observe that the text 'How are you doing today?' is displayed as shown below -



Hence we have used write( ) method of FileWriter I/O Class to write text to the text file.








Please comment below to feedback or ask questions.

Append text in a file using append( ) method of FileWriter I/O Class will be explained in the next post.





No comments: