Files are the most complicated concept in any programming language.In this tutorial we shall make it simpler by learning some basic techniques in File.There are two types of operation done on files.First, we can write the data into the file.The other operation is reading the data from the file.We shall go in detail now..
To write the data into a file we use the class FileOutputStream and the methods defined in that class.To utilize the methods defined in this class we need to create the objects for this class.There is a constructor defined for this class and the general form of this constructor is
FileOutputStream(String filepath);
For creating an object we use the following syntax.
FileOutputStream fis = new FileOutputStream("name_of_the_file");
With this we have created the objects for the class,now we need to invoke the suitable method defined in the class for writing the data.For this we use the method write() with the data to be wrote has a parameter.The main step in using the FileOutputStream is,whenever we are writing the data we need to convert the data into bytes.
import java.io.*; class fileswritedemo { public static void main(String arg[]) { try { String str="I Love Java Programming"; byte b[] = str.getBytes(); FileOutputStream fos = new FileOutputStream("fi.txt"); for(int i=0;i<b.length;i++) { fos.write(b[i]); } fos.close(); } catch(Exception e) { System.out.print(e); } } }
Pingback: Creating and Writing Excel file in Java | letusprogram...!!!
Pingback: Copying data from one file to other file using java | letusprogram...!!!