how to create File and write into file in Java

How to create File and write into that using java

  • IO package is used to perform Input/Output operation or file operation .  
    package Name:--> import java.io
  • FileWriter is used to check file is there or not if not it will throw "File not found Exception ". but we can overcome this problem using
       FileWriter fw = new FileWriter(file.getAbsoluteFile());
       if(!file.exists()){
       file.createNewFile();//Force to create File with Empty content
       }
  • File operation will force to progammer to put File operation code inside try catch else throw IO Exception because JVM don't know run time wheather file is avilable on directroy or not .or any other reason that is handle by IO Exception 
Example :-


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileOperation {
public static void main(String[] args) {
String filepath=null;
// TODO Auto-generated method stub

try {
filepath=System.getProperty("user.home")+System.getProperty("file.separator")+"Hello.txt";
System.out.println(filepath);
File file = new File(filepath);

if (!file.exists()) {//File is already there 
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Hi Anand");
bw.newLine();
bw.write("welcome in Java World");
bw.close();
}else{
file.createNewFile();//Force to create File with Empty content
System.out.println("File created With Empty Content");
}

System.out.println("File created and write sucessfully");

} catch (Exception e) {
e.printStackTrace();
}
}
}

Comments

Popular posts from this blog

Converting JSONArray into CSV file in java

Online Book Store Website Using Java

How to read CSV File in Java