Write to a File in Java IO - 3 Simple Ways

Write to a File in Java IO is easy to do with the three little methods different from each other in FileOutputStream class does the thing. Here is a Java Tutorial to achieve this.


import java.io.*;
class FileWrite
{
public static void main(String args[]) throws Exception
{
// Create a string to write to
String st="I am going to be written in the file.";
// First way
// Create FileOutputStream object
FileOutputStream fout=new FileOutputStream("output.txt");
// Convert string to bytes
byte[] b=st.getBytes();
// Write the byte array
fout.write(b);
// close fout
fout.close();
// Second way
FileOutputStream fout1=new FileOutputStream("output1.txt");
// Convert string to char array
char[] c=st.toCharArray();
for(int i=0;i<c.length;i++)
{
fout1.write(c[i]);
}
fout1.close();
// Third way
FileOutputStream fout2=new FileOutputStream("output2.txt");
byte[] b1=st.getBytes();
fout2.write(b1,0,b1.length);
fout2.close();
}
}
String st: The string which will be written in the file.
getBytes(): Convert the string into a byte array that contains ascii values of each character in the string in order.
fout.write(b): Write the byte array to the file output.txt because fout points to that file only.
toCharArray(): Convert the string to char array of length of the string and containing all the characters in the string in order.
fout1.write(c[i]): Write each character in the string to the file. The method take int, but the char is automatically treated as int i.e. the ascii value will be sent and then be written to output1.txt
fout2.write(b1,0,b1.length): Write the byte array from index '0' till the length of the array i.e. till the end. You can alternatively, write partially by specifying the start and the end index in the last two parameters of the method that we are discussing in this paragraph.


Posted by at on

Tags: Java IO,