How to Create File in Java using FileOutputStream Class
Classes used in this program:-
1) FileOuputStream Class - FileOuputStream Class is used to write data into in a file.
2) Scanner Class - Used to take input form user.
Program to create a File:-
import java.io.FileOutputStream;
import java.util.Scanner;
public class createfile
{
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the file name: ");
String name=sc.nextLine();
FileOutputStream fos=new FileOutputStream(name, true);
System.out.print("Enter file content: ");
String str=sc.nextLine()+"\n";
byte[] b= str.getBytes();
fos.write(b);
fos.close();
System.out.println("file saved.");
sc.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output -
Enter the file name: CodingEazy
Enter file content: Coding is Easy.
file saved.
Where the file is going to save?
The file will saved in the directory where you save the above program. E.g. If you save your program in "Coding" folder then the program will directly save in the specific folder.
0 Comments