How to Create a File with a Specific charset in Java ?In Java, in order to create a file with a given charset, we must supply the character encoding when writing text to a file. Classes to produce Java files with a certain character set: The OutputStreamWriter class and a FileOutputStream allow us to create Java files with a certain charset. Data can be stored in a file using the FileOutputStream OutputSream class. Choosing the charset to use when writing to a file is made possible by the OutputStreamWriter class. The article will teach us how to use a specified charset when creating a file in Java. Example 1:There are three parameters required for the writeToFileWithCharset function. Next, the content is written into the file with the provided charset using a FileOutputStream and an OutputStreamWriter inside the writeToFileWithCharset method. There are two categories in the primary method. The first one uses the UTF-8 character set, whereas the second one uses the ISO-8859-1 character set. The software controls file operations inside a try-with-resources block to guarantee appropriate resource allocation, and it outputs a message after a file is successfully created. Implementation:FileName: CreateCharsetFile.java Output: The file is created with the charset: UTF-8 The file is created with the charset: ISO-8859-1 Example2:Using the Windows-1252 character set, the provided Java program creates a file called "HelloWorld.txt" and inserts the given string into it. Using the file name, content, and character set as inputs, the FileWithCharset method manages the file creation and writing operation. To write the content to the file with the given charset, it makes use of an OutputStreamWriter and a FileOutputStream. An IOException is caught and displayed if it happens during this process. The main function creates a file, sets its name and contents, and then uses the Windows-1252 charset to write a file by calling FileWithCharset. Implementation:FileName: UsingWindows1252.java Output: The file is created with the charset: windows-1252 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India