×

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

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Java Database Connectivity with Oracle

JDBC: A Programmer can develop a complete application using the Java built-in API’s. So, for storing the data required for solving a real-world problem is stored into a database. To connect...

5 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.