×

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it is being used to begin writing character-oriented data to a file in Java.

As there are numerous classes and methods in Java that can achieve the following objectives, there are numerous ways to write into a file:

  1. Utilizing the writeString() method
  2. Applying the FileWriter Class
  3. BufferedWriter Class Utilization
  4. Employing the FileOutputStream Class

Utilizing the writeString() method

Java 11 is compatible with this technique. Four parameters are available for this approach. The file path, character set, charset, and options fall under this category. In order for this method to write to a file, the very first two parameters are necessary. The contents of the file are written as characters. It can throw four different exception kinds and returns the file path. It is preferable to utilize when the file's content is brief.

Example

 It demonstrates how to put data together into a file using the Files class'writeString() function. To associate the filename with the path where the information will be written, a different class called Path is used. The readString() function of the Files class can be used in code to read the content of any already-existing file and verify that it was properly written there.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Demo {
	public static void main(String[] args)
		throws IOException
	{
		String text = "Hello world";
		Path fileName = Path.of("/Users/sravani/Desktop/demo.docx");
		Files.writeString(fileName, text);
                             String file_content = Files.readString(fileName);
		System.out.println(file_content);
	}
}

Output

Hello world

Applying the FileWriter Class

Another preferable choice is to write into the file utilisingFileWriter class if the file's content is brief. Like the writeString() method, it also writes the character stream as the file's content. The default characters encoding as well as buffer size in bytes are set in the function Object() of this class.

The utilization of the FileWriter class for write material into a file is demonstrated in the example below. To write into a file, a FileWriter class object must be created and contain the filename. The content of the string variable is then written to the file using the write() method. An IOException will be thrown and the error message displayed from the catch block if any errors are made when writing the file.

Example

import java.io.FileWriter;
import java.io.IOException;


public class Demo {
public static void main(String[] args)
	{
		String text	="Hello world";
		try {
			FileWriterfWriter = new FileWriter("/Users/sravani/Desktop/demo.docx");
			fWriter.write(text);
			System.out.println(text);
			fWriter.close();
			System.out.println("File created successfully ");
           }
		catch (IOException e) {
			System.out.print(e.getMessage());
		}
	}
}

Output

File created successfully

BufferedWriter Class Utilization

Text can be written to a character output stream using it. Although a huge buffer size can be provided, a default buffer size is present. It is helpful for writing strings, characters, and arrays. If there is no need for prompt output, it is preferable to wrap this class in any writer class when writing data to a file.

The use of the BufferedWriter class to write into a file is demonstrated in the following example. In order to write content into the file, an object of the BufferedWriter class, similar to FileWriter, must be created. However, this class makes use of a huge buffer size to facilitate writing enormous amounts of text into the file.

Example

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Demo {
	public static void main(String[] args)
	{
		String text= "Hello world";
		try {
			BufferedWriterf_writer = new BufferedWriter(new FileWriter("/Users/sravani/Desktop/demo.docx"));
			f_writer.write(text);
			System.out.print(text);
			System.out.print("File created successfully");
			f_writer.close();
		}
		catch (IOException e) {
			System.out.print(e.getMessage());
		}
	}
}

Output

File created successfully

Employing the FileOutputStream Class

Raw stream data is written using it in a file. The FileWriter, as well as BufferedWriter classes, only support writing text to files; the FileOutputStream class supports writing binary data. Use of the FileOutputStream class in the example that follows shows how and where to read or write into a file

To write data into a file, the class object with the filename must also be created. Here, using the write() method, the string content is transformed into a byte array and written to the file.

Example

import java.io.FileOutputStream;
import java.io.IOException;
public class Demo {
	public static void main(String[] args)
	{
		String fileContent = "Hello World";
		FileOutputStreamoutputStream = null;
		try {
			outputStream = new FileOutputStream("file.txt");
			byte[] strToBytes = fileContent.getBytes();
			outputStream.write(strToBytes);
			System.out.print(
				"File created successfully ");
		}
		catch (IOException e) {
			System.out.print(e.getMessage());
		}
		finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				}


				catch (IOException e) {
					System.out.print(e.getMessage());
				}
			}
		}
	}
}

Output

File created successfully

Related Topics

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.