×

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

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.