Write a Java Program to Create File and Write to the File

Java Program to Create File and Write to the File

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Create File and Write to the File
Java Program to Create File and Write to the File

Write a Java Program to Create File and Write to the File

PROGRAM: Java Program to Create File and Write to the File

/*Java Program to Create File and Write to the File*/

 1: Java Program to Create a File

// importing the File class
import java.io.File;

class Main {
public static void main(String[] args) {

// create a file object for the current location
File file = new File(“JavaFile.java”);

try {

// create a new file with name specified
// by the file object
boolean value = file.createNewFile();
if (value) {
System.out.println(“New Java File is created.”);
}
else {
System.out.println(“The file already exists.”);
}
}
catch(Exception e) {
e.getStackTrace();
}
}
}

2: Java Program to Write Content to the File

// importing the FileWriter class
import java.io.FileWriter;

class Main {
public static void main(String args[]) {

// creates a multiline string using + operator
// the string is a Java Program
String program = “class JavaFile { ” +
“public static void main(String[] args) { ” +
“System.out.println(\”This is file\”);”+
“}”+
“}”;
try {
// Creates a Writer using FileWriter
FileWriter output = new FileWriter(“JavaFile.java”);

// Writes the program to file
output.write(program);
System.out.println(“Data is written to the file.”);

// Closes the writer
output.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *