Create file in java and write to file

Java create & write to file Examples [Multiple Methods]

Related Searches: java write to file, java write string to file, how to write to a file in java, java write to text file, java output to file, java write to file line by line, how to write to a file, read and write file in java, java create text file, java save file, write string to file, string to file, java print to file, how to write to a text file in java, create new file and write in java, java code to write to a file, how to output to a file in java, how to make a text file in java, export file java, java save, file write in java example, write content to file, java program to write a file, write in a text file in java

Introduction to Java create file and Java write to file

A file is simply a storage of data items. We can store a large amount of data in a file and use it later whenever necessary. In this tutorial, we will learn how we can create a Java file and how we can write on it. The java language provides many methods and classes to achieve creating and writing a file task.

Читайте также:  Python строка включает строку

Later in this tutorial, we will learn some of these methods including Java.io.File , Java.io.FileOutputStream , and NIO Files.write() method to create java files by taking different examples. Moreover, we will also discuss various methods to write in java files including bufferedWriter , printWriter , fileOutputStream , dataOutputStream , and randomAccessFile by taking various examples. All in all, this tutorial is going to help to create a java file and write on it using various methods.

Getting started with Java create file

A simple definition of a file could be a collection of data stored in one unit, identified by a filename. It can be a document, picture, audio or video stream, data library, application, or other collection of data. Java provides us multiple ways to create files. In this section, we will discuss some of those methods along with taking examples.

Example-1: Java create file using Java.io.File class

This Java.io.File is the first and the most commonly used method for creating a file in Java. We use the method createNewFile() of the java.io.File class. While initializing the object of the File class, we provide the name of the file which we want to create. After creating this object, we call the createNewFile() method with this object.

This method creates a new file in Java. Its return type is boolean. Moreover, It returns true if the file is created successfully, else false if the file with the given name already exists.

Now let us take an example and see how we can use this method to create a java file. See the example below:

// importing java.io.file library import java.io.File; // Importing java.io.IOException library import java.io.IOException; // main class public class Main < public static void main(String[] args) < // try block try < // java create file File myFile = new File("MyFile.txt"); // check if file created or not. boolean created = myFile.createNewFile(); // If statement if (created) < System.out.println("File has been created successfully!!"); >else < System.out.println("File already present!!"); >> // to catch any IO exceptions that might occurs catch(IOException e) < System.out.println("Exception Occurred:"); e.printStackTrace(); >> >
File has been created successfully!!

Also, see the screenshot which shows the newly created file.

Читайте также:  Java implements abstract method

Java create & write to file Examples [Multiple Methods]

Notice that on the left side it created a file named «myFile.txt». Also, it is always a good practice to use try-catch blocks to handle any kind of exception that might occurs during the creating of a java file. You can read more about the syntax of the try-catch block from the article try-catch method in java.

Now, we already had created the file and if we again run the same code, we will get the following output:

We get this message because our condition of creating a new file becomes false as the above method returns false if the file is already exists.

Example-2: Java create file using Java.io.FileOutputStream class

Here is another method of creating a file in Java. This class creates a new file at the specified path and also can write or add the content to it which we will learn in the next section. But here we will use this method to create a file. See the example below which creates the file name «myFile2.txt» in the same directory.

// Importing java.io.FileOutputStream library import java.io.FileOutputStream; // importing java.io.IOException import java.io.IOException; // main class public class Main < // java main method which throws exception if accurs public static void main(String args[])throws IOException < // java create file try(FileOutputStream fileOutputStream = new FileOutputStream("myFile2.txt"))< System.out.println("Successfully java create file!!"); >> >
Successfully java create file!!

See the screenshot below as well which shows the newly created java file.

java create file

Notice that a new file has been created which is shown on the left side.

Example-3: Java create file using NIO Files.write() method

Another method is considered one of the best methods to create a file in Java. It is because there are no complexities or worries to close the file resources. This class is located in the java.nio.file package. Now let us take an example and create a new file named » myFile3 «.

// importing java.io.IOException library import java.io.IOException; // importing NIO import java.nio.file. * ; // main class public class Main < public static void main(String[] args) < // java create file Path myFile = Paths.get("myFile3.txt"); // try block try < // check if file has been created or not!! Path check = Files.createFile(myFile); System.out.println("Java file created: " + check); >// catch block catch(IOException e) < System.out.println("Exception Occurred:"); >> >
Java file created: myFile3.txt

Check the screenshot below as well which shows the newly created file.

java create file

Notice that we successfully created a new file named «myFile.txt», which can be seen on the left side.

Creating different types of files with Java

So far if you have noticed, we had created only one type of file using various methods. It is also possible to create different types of methods. You can choose any of the above methods that is easy for you and create different types of files. All you need to do is replace the extension .txt with the type of file that you want to create. For example, see the following example which creates various types of files.

// Importing java.io.FileOutputStream library import java.io.FileOutputStream; // importing java.io.IOException import java.io.IOException; // main class public class Main < // main method public static void main(String args[])throws IOException < try< // create txt file FileOutputStream txtFile = new FileOutputStream("Myfile.txt"); // creating python file FileOutputStream pythonFile = new FileOutputStream("PythonFile.py"); // creating java file FileOutputStream JavaFile = new FileOutputStream("JavaFile.java"); // creating csv file FileOutputStream CSVfile = new FileOutputStream("MyCSV.csv"); >finally < System.out.println("Files created!!"); >> >

Now let us look at the newly created files. See the image below:

Java create & write to file Examples [Multiple Methods]

Notice that we created various different types of files using java.

Getting started with Java write to file

Now we are good at creating files in java using various. But those files are useless until we will not add any data to them. Java provides us different ways to write on a file. In this section, we will explore some of those libraries and methods that are used in java to write on file and we will take various examples as well. For each case, we will take an empty file named «myFile.txt» and will add different data to it.

Example-1: Java write to file with bufferedWriter method

The very first method that we will use to write or add data to our text file named «myFile.txt» is bufferedWriter. We have to import a couple of libraries to use the buffered writer method as shown in the program below: Let now take the example and see how we can add data to our empty txt file.

// Importing bufferedwriter library import java.io.BufferedWriter; // importing file writer import java.io.FileWriter; // importing java.io.IOException import java.io.IOException; // main class public class Main < // java main method which throws exception if accurs public static void main(String args[])throws IOException < // string data type String string = "Welcome to go linux cloud!!"; // creating new buffered object BufferedWriter writer = new BufferedWriter(new FileWriter("MyFile.txt")); // adding the data to our java file writer.write(string); // closing the file after editing writer.close(); >>

When we run the code, the following data will be added to the file. See the output below:

java write to file

Notice that we successfully added the required data to our file. We can also add data to existing data as well. See the following example which adds more data to our file which already has some data.

// Importing bufferedwriter library import java.io.BufferedWriter; // importing file writer import java.io.FileWriter; // importing java.io.IOException import java.io.IOException; // main class public class Main < // java main method which throws exception if accurs public static void main(String args[])throws IOException < // string data type String string = " And welcome to java tutorials"; // creating new buffered object BufferedWriter writer = new BufferedWriter(new FileWriter("MyFile.txt", true)); // adding the data to our java file writer.write(string); // closing the file after editing writer.close(); >>

Now let us see the text file:

java write to file

In the program notice that the FileWriter() takes and options parameter to override a file or adding data to existing data.

Example-2: Java write to file with printWriter method

Now let us use another method to write or add data to an existing file. We will use printWriter method to add string data to our already existing file named «MyFile.txt». See the example below:

// importing java.io.IOException import java.io.IOException; import java.io.PrintWriter; // main class public class Main < // java main method which throws exception if accurs public static void main(String args[])throws IOException < // string data type String string = "You are now reading this file!!"; // creating new object PrintWriter adding = new PrintWriter("MyFile.txt"); // adding data to file adding.printf(string); // closing file adding.close(); >>

When we run the code, the following data will be added to our file. See the output below:

java file write

Notice that we had successfully added the data to our file.

Example-3: Java write to file with fileOutputStream

Another method to add data to our existing file in java is fileOutputStream method. This is one of the usefull methods to write on files in java. See the example below which uses this method to add string data to our existing file.

 // importing java.io.IOException import java.io.FileOutputStream; import java.io.IOException; // main class public class Main < // java main method which throws exception if accurs public static void main(String args[])throws IOException < // string data type String str = "Hello!! This is bashir alam"; //creating new object FileOutputStream outputStream = new FileOutputStream("MyFile.txt"); // adding in form of bytes array byte[] adding = str.getBytes(); outputStream.write(adding); // closing file outputStream.close(); >>

The following data will be added to the text file.

java write to file

Notice that we successfully added the string data to our file.

Example-4: Java write to file with randomAcessFile

Now let us use another method to write and add data to an existing file. This method is called randomAcessFile method, which enables us to write at a specific position in the file given the offset, from the beginning of the file. See the example below:

// importing java.io.IOException import java.io.IOException; import java.io.RandomAccessFile; // main class public class Main < // java main method which throws exception if accurs public static void main(String args[])throws IOException < // string data type String string = "Welcome to golinuxcloud!!"; //creating new object RandomAccessFile writer = new RandomAccessFile("MyFile.txt", "rw"); // adding data to file writer.writeChars(string); // closing file writer.close(); >>

java write to file

Notice that we successfully added the string data to our file.

Summary

We already discussed that a file is a collection of data stored in one unit, identified by a filename. In programming, files are used to store a large amount of data and can be used later. In this tutorial, we learned about java creating files and java writing on files. We learned various methods to create files by taking examples and creating files. Moreover, we also discussed different ways to write or add data to existing files. All in all, this tutorial covers all the necessary and important classes and methods that are used in file handling.

Further Reading

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

Java Tutorial

  • Set Up Java Environment
    • Set Up Java on Linux
    • Set up Java with BlueJ IDE
    • Set up Java with VSC IDE
    • Set up Java with Eclipse IDE
    • Java Multiline Comments
    • Java Variables
    • Java Global Variables
    • Java Date & Time Format
    • Different Java Data Types
    • Java Booleans
    • Java Strings
    • Java Array
    • Java Byte
    • Java convert list to map
    • Java convert double to string
    • Java convert String to Date
    • Java convert Set to List
    • Java convert char to int
    • Java convert long to string
    • Java Operators Introduction
    • Java Boolean Operators
    • Java Relational Operators
    • Java Arithmetic Operators
    • Java Bitwise Operators
    • Java Unary Operators
    • Java Logical Operators
    • Java XOR (^) Operator
    • Java Switch Statement
    • Java If Else Statement
    • Java While Loop
    • Java For / For Each Loop
    • Java Break Continue
    • Java Nested Loops
    • Java throw exception
    • Java Try Catch
    • Java Accessor and Mutator Methods
    • Java main() Method
    • IndexOf() Java Method
    • Java ListIterator() Method
    • Java create & write to file
    • Java read file
    • Java Parameter
    • Java Argument
    • Java Optional Parameters
    • Java Arguments vs Parameters
    • Java Arrays.asList
    • Java HashSet
    • Java Math
    • Java HashMap vs Hashtable vs HashSet
    • Java LinkedList
    • Linked List Cycle
    • Java List vs LinkedList
    • Java ArrayList vs LinkedList

    Источник

    Java Create and Write To Files

    To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try. catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):

    Example

    import java.io.File; // Import the File class import java.io.IOException; // Import the IOException class to handle errors public class CreateFile < public static void main(String[] args) < try < File myObj = new File("filename.txt"); if (myObj.createNewFile()) < System.out.println("File created: " + myObj.getName()); >else < System.out.println("File already exists."); >> catch (IOException e) < System.out.println("An error occurred."); e.printStackTrace(); >> > 

    To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the » \ » character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt

    Example

    File myObj = new File("C:\\Users\\MyName\\filename.txt"); 

    Write To a File

    In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method:

    Example

    import java.io.FileWriter; // Import the FileWriter class import java.io.IOException; // Import the IOException class to handle errors public class WriteToFile < public static void main(String[] args) < try < FileWriter myWriter = new FileWriter("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!"); myWriter.close(); System.out.println("Successfully wrote to the file."); >catch (IOException e) < System.out.println("An error occurred."); e.printStackTrace(); >> > 

    To read the file above, go to the Java Read Files chapter.

    Источник

Оцените статью