Java Create and Write Files

We are going to discuss how to create files in Java with examples, in the hopes of meeting your learning objectives.



Java Create Files – TXT

Regarding Java file creation, the createNewFile() method can be used to create a file.

When this method executes, a boolean value is returned: if the file was successfully created, then it returns true, and if it was already existing, then it returns false.

This article illustrates how to create four different types of files using the createnewfile() method.

  1. .txt file (Text Document File)
  2. .pdf file (Portable Document Format)
  3. .csv file (comma-separated values Format)
  4. .JSON file (JavaScript Object Notation)

A try-catch block surrounds the method. Due to the fact than an IOException will be thrown if there is an error (if the file cannot be created for some reason):

Create txt File Example: 

import java.io.File; // File class is imported from the java.io package import java.io.IOException; // To handle errors, import the IOException classpublic class Main { public static void main(String[] args) { try { File mrx_Obj = new File("FirstFile.txt"); if (mrx_Obj.createNewFile()) { System.out.println("File is Successfully created: " + mrx_Obj.getName()); } else { System.out.println("The File "+mrx_Obj.getName()+" already exists");} } catch (IOException e) { System.out.println("An error has generated during the creation of the file"); e.printStackTrace(); } } }

 

Java Create txt File examples

Create txt File Example:2 

import java.io.File; import java.io.IOException;public class Main { public static void main(String[] args) {try { File ample_Obj=new File("SecondFile.txt"); if (ample_Obj.createNewFile()){ System.out.println("New File is created : "+ample_Obj.getName()); } else { System.out.println(ample_Obj.getName()+" file already exists in the directory"); }} catch (IOException e){ System.out.println("An error occurred while creating file"); } } }

Creating Java files in a specific directory requires specifying the path and escaping the “” character by double backslashes (for Windows).

On the other hand, you can just write the path, such as: /Users/name/filename.txt, on Macs and Linux.

Create txt File Example:3 

import java.io.File; import java.io.IOException;public class Main{ public static void main(String[] args) { try { File myObj = new File("mrexample\\java\\NewFile.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }

 

Create txt File Example:4 

import java.io.File; import java.io.IOException;public class Main{ public static void main(String[] args) { try { File myObj = new File("mrexample\\java\\AnotherFile.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }

 


Java Create PDF File

A Portable Document File can be easily created by adding an extension of (.pdf) to the file name while using the java’s createNewFile() method.

The given examples will teach you how to make a pdf file easily:

Create PDF File Example:1 

import java.io.File; import java.io.IOException; // Handles the exceptions during the creation of file import org.apache.pdfbox.pdmodel.PDDocument; // Create Template of Pdf files import org.apache.pdfbox.pdmodel.PDPage; // Create Border,Model of the Pdf filepublic class Main{ public static void main(String args[]) throws IOException { PDDocument mrx_pdf= new PDDocument(); mrx_pdf.addPage(new PDPage()); // A builtin method to add pages to the created pdf // Saves the file FirstPdf to the system mrx_pdf.save("FirstPdf.pdf"); // Prints the message upon successful creation of pdf file System.out.println("The PDF file is successfully created by the name FirstPdf.pdf"); // document should be closed after being created mrx_pdf.close(); } }

 

We can also create the .pdf file in any specific folder or directory, as shown by the examples below:

Here we create the .pdf file in public directory using java’s createNewFile() method:

Create PDF File Example:2 

public class Main{ public static void main(String args[]) throws IOException { PDDocument mrx_pdf= new PDDocument(); mrx_pdf.addPage(new PDPage()); // A builtin method to add pages to the created pdf // Shows the path of the PDF file mrx_pdf.save("mrexample\\java\\NewFile.pdf"); // Prints the message upon successful creation of pdf file System.out.println("The PDF file is successfully created by the name My_NewPDF"); // document should be closed after being created mrx_pdf.close(); } }

 


Java Create CSV File

Comma Separated Value File can be easily created by adding an extension of (.csv) to the file name while implementing the java’s createNewFile() method.

The given examples will guide you how to do it easily:

Example: 

import java.io.File; // File class is imported from the java.io package import java.io.IOException; // To handle errors, import the IOException classpublic class Main { public static void main(String[] args) { try { File ample_csv = new File("MyFirstCsvFile.csv"); if (ample_csv.createNewFile()) { System.out.println("Csv File is Successfully created: " + ample_csv.getName()); } else { System.out.println("The File "+ample_csv.getName()+" already exists");} } catch (IOException e) { System.out.println("An error has generated during the creation of the file"); e.printStackTrace(); } } }

Example: 

import java.io.File; // File class is imported from the java.io package import java.io.IOException; // To handle errors, import the IOException classpublic class Main { public static void main(String[] args) { try { File ample_csv = new File("MySecondCsvFile.csv"); if (ample_csv.createNewFile()) { System.out.println("Csv File is Successfully created: " + ample_csv.getName()); } else { System.out.println("The File "+ample_csv.getName()+" already exists");} } catch (IOException e) { System.out.println("An error has generated during the creation of the file"); e.printStackTrace(); } } }

Given example shows the creation of .csv file in public directory using java’s createNewFile() method:

Example: 

import java.io.File; import java.io.IOException;public class Main{ public static void main(String[] args) { try { File myObj = new File("mrexample\\java\\NewFile.csv"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }

 


Java Create JSON File

Java Script Object Notation file can be formed similarly by adding the extension .json to the file name while constructing it using java createNewFile() method:

Example: 

import java.io.File; // File class is imported from the java.io package import java.io.IOException; // To handle errors, import the IOException classpublic class Main { public static void main(String[] args) { try { File mrx_json = new File("MyFirstJSONFile.json"); if (mrx_json.createNewFile()) { System.out.println("First JSON File is Successfully created named : " + mrx_json.getName()); } else { System.out.println("The File "+mrx_json.getName()+" already exists");} } catch (IOException e) { System.out.println("An error has generated during the creation of the file"); e.printStackTrace(); } } }

Example: 

import java.io.File; // File class is imported from the java.io package import java.io.IOException; // To handle errors, import the IOException classpublic class Main { public static void main(String[] args) { try { File ample_json= new File("MySecondJSONFile.json"); if (ample_json.createNewFile()) { System.out.println("Another JSON File is Successfully created named : " + ample_json.getName()); } else { System.out.println("The File "+ample_json.getName()+" already exists");} } catch (IOException e) { System.out.println("An error has generated during the creation of the file"); e.printStackTrace(); } } }

A .json extension file can be created in a public directory by using Java’s createNewFile() method as shown in the following example:

Example: 

import java.io.File; import java.io.IOException;public class Main{ public static void main(String[] args) { try { File myObj = new File("mrexample\\java\\NewFile.json"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }

 


Write TXT File In Java

To write some text to the file we created above, we use the FileWriter class and its write() method.

In Java create files, you should close the file after you are finished writing.

We have written and closed the files afterwards, which were created in the examples of creating a file in a specific directory above.

In the example below, we have written successfully to the .txt file:

Example: 

import java.io.File; import java.io.FileWriter; // The FileWriter class from the java.io package is imported here import java.io.IOException; // The errors can be handled by importing the IO.Exception class public class Main{ public static void main(String[] args) { try { File ample=new File("FirstFile.txt"); FileWriter mrx_write=new FileWriter("FirstFile.txt"); mrx_write.write("Hey ! we are writing this sentence to the First File we create"); mrx_write.close(); System.out.println("The file: "+ample.getName()+" is successfully written and closed"); } catch (IOException e) { System.out.println("An error is generated while writing to the file"); e.printStackTrace(); } } }

Example: 

import java.io.File; import java.io.FileWriter; // The FileWriter class from the java.io package is imported here import java.io.IOException; // The errors can be handled by importing the IO.Exception class public class Main{ public static void main(String[] args) { try { File ample=new File("SecondFile.txt"); FileWriter mrx_write=new FileWriter("SecondFile.txt"); mrx_write.write("Hey !\nWe are learning how to write to a file \nIn this programme we are writing the text to the File"+ample.getName()+" using the write method \nAnd will close it using the close() method");mrx_write.close(); System.out.println("The file: "+ample.getName()+" is successfully written and closed"); } catch (IOException e) { System.out.println("An error is generated while writing to the file"); e.printStackTrace(); } } }

Write PDF File In Java

Similarly, We can also write to the .pdf file we created above in public directory:

Example: 

import java.io.FileNotFoundException; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; public class GeneratePdf { public static void main(String args[]) { //created PDF document instance Document doc = new Document(); try { //generate a PDF at the specified location PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("mrexample\\java\\SecondPdf.pdf")); System.out.println("Your pdf is created successfully."); //opens the PDF doc.open(); //adds paragraph to the PDF file doc.add(new Paragraph("We are writing this sentence to the SecondPdf.pdf file")); //close the PDF file doc.close(); System.out.println("Your pdf is written and closed successfully.");//closes the writer writer.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }

 


Write CSV File In Java

Given example shows the method of writing to a .csv file:

Example: 

import java.io.File; import java.io.FileWriter; // The FileWriter class from the java.io package is imported here import java.io.IOException; // The errors can be handled by importing the IO.Exception class public class Main{ public static void main(String[] args) { try { File ample=new File("NewFile.csv"); FileWriter mrx_write=new FileWriter("NewFile.csv"); mrx_write.write("Hey ! we are writing this sentence to the Csv file we created"); mrx_write.close(); System.out.println("The file: "+ample.getName()+" is successfully written and closed"); } catch (IOException e) { System.out.println("An error is generated while writing to the file"); e.printStackTrace(); } } }

Write JSON File In Java

The following example shows how to write to a JSON file:

Write Json File Example: 

import java.io.File; import java.io.FileWriter; // The FileWriter class from the java.io package is imported here import java.io.IOException; // The errors can be handled by importing the IO.Exception class public class Main{ public static void main(String[] args) { try { File ample=new File("NewFile.json"); FileWriter mrx_write=new FileWriter("NewFile.json"); mrx_write.write("[{'Title': 'Developer',\n 'Programming Language': 'Java Programming Language', \n 'isJavaEasy': 'true'}]"); mrx_write.close(); System.out.println("The file: "+ample.getName()+" is successfully written and closed"); } catch (IOException e) { System.out.println("An error is generated while writing to the file"); e.printStackTrace(); } } }

 


For more information on reading the files above, please refer to the article on reading files in Java.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

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