Open In App

How to Create a File with a Specific charset in Java?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, when we write text to a file, we must provide the character encoding to create a file with a specified charset.

Classes to generate Java Files with Specified Charset

Using a FileOutputStream and the OutputStreamWriter class we can generate a Java file with a specified charset.

  • FileOutputStream: It is an OutputSream class used for storing data in a file.
  • OutputStreamWriter: This class lets us choose the charset when we write something to a file.

In this article, we will learn how to create a file with a specific charset in Java.

Program to Create a File with a Specific Charset in Java

Below is the implementation of the Program to Create a File with a Specific Charset:

Java




// Java Program to Create a File
// With a Specific charset
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
  
// Driver Class
public class CharsetExample {
    public static void writeToFileWithCharset(String fileName, String content, Charset charset) 
    {
        try (FileOutputStream fileOutputStream = new FileOutputStream(fileName);
             OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charset)) 
        {
            // writing content to the file
            outputStreamWriter.write(content);
  
            System.out.println("File created with charset: " + charset);
        } catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
  
      // Main Function
    public static void main(String args[]) 
    {
        String fileName = "output.txt";
        String content = "Hello, this is a file with a specific charset.";
        
        // Using UTF-8 Charset
        writeToFileWithCharset(fileName, content, StandardCharsets.UTF_8);
          
          // Using ISO-8859-1 Charset
        writeToFileWithCharset(fileName, content, Charset.forName("ISO-8859-1"));
    }
}


Output

File created with charset: UTF-8
File created with charset: ISO-8859-1

Explanation of the above Program:

In the above program,

  • The writeToFileWithCharset method takes three parameters.
  • After this, inside the writeToFileWithCharset method, a FileOutputStream and an OutputStreamWriter are used to write the content into the file with specified charset.
  • In main method, two types are there. First one using UTF-8 charset and the other one is using ISO-8859-1 charset.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads