Table of Contents
Constructors in FileWriter in Java
Methods of FileWriter in Java
Examples to Implement FileWriter in Java
Example #4
Conclusion
Recommended Article
Home Java javaTutorial FileWriter in Java

FileWriter in Java

Aug 30, 2024 pm 03:37 PM
java

FileWriter in java is used to create files, and characters can be written into the created file; output stream class is the base class of FileWriter class as it is being inherited from it, and the assumption made by the constructor of this class is that default character encoding and default byte buffer size are permitted if these values are to be specified by us an output stream writer must be constructed on a file output stream.

Declaration of Java FileWriter Class:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Java.lang.Object
Java.io.Writer
Java.io.OutputStreamWriter
Java.io.FileWriter
Copy after login

Constructors in FileWriter in Java

The FileWriter class in java consists of several constructors. They are:

  • FileWriter(File file): When a file object is given, a FileWriter object is constructed by using this method FileWriter(File file).
  • FileWriter(File file, Boolean append): When a file object is given, a FileWriter object is constructed, and the Boolean value indicates whether to append the data that is being written or not using this method FileWriter(File file, Boolean append).
  • FileWriter(FileDescriptor fd): A FileWriter object is constructed, which is associated with the file descriptor specified as a parameter in the method FileWriter(FileDescriptor fd).
  • FileWriter(String fileName): When a file name is given, a FileWriter object is created using this method FileWriter(String fileName).
  • FileWriter(String filename, Boolean append): When a file name is given, a FileWriter object is created, and the Boolean value indicates whether to append the data that is being written or not using this method FileWriter(String filename, Boolean append).

Methods of FileWriter in Java

The FileWriter class in java consists of several methods, which are:

  • Public void write(int c) throws IOException: A single character is written using this method; public void write(int c) throws IOException.
  • Public void write(char [] stir) throws IOException: An array of characters is written using this method. Public void write(char [] stir) throws IOException.
  • Public void write(string str) throws IOException: A string is written using this method. Public void write(string str) throws IOException.
  • Public void write(string str, int off, int len) throws IOException: A portion of a string is written using this method Public void write(string str, int off, int len) throws IOException where off indicates offset from which the writing of the characters must begin and len indicates the number of characters to be written.
  • Public void flush() throws IOException: The stream is flushed using this method Public void flush() throws IOException.
  • Public void close() throws IOException: The stream is first flushed, and the writer is then closed using this method Public void close() throws IOException.

Examples to Implement FileWriter in Java

Below are the examples of implementing FileWriter in Java:

Example #1

Java program to demonstrate the creation of FileWriter class.

 Code:

import java.io.*;
public class Read {
public static void main(String args[])throws IOException {
File file1 = new File("check.txt");
// A file is created
file1.createNewFile();
// Object of FileWriter is created
FileWriter writer1 = new FileWriter(file1);
// Contents are written to the file
writer1.write("Welcome to FileWriter");
writer1.flush();
writer1.close();
// Object of filereader is created
FileReader read = new FileReader(file1);
char [] a1 = new char[50];
read.read(a1);   // array contents are read
for(char ch : a1)
System.out.print(ch);   // characters are printed one by one
read.close();
}
}
Copy after login

Output:

FileWriter in Java

Example #2

Java program to using FileWriter class to create a text file.

Code:

import java.io.*;
public class Example {
public static void main(String[] args) {
//File constructor is initialized
File file1 = new File("C:/Users/shivakumarsh/Desktop/Learning/source.txt");
try {
boolean create = file1.createNewFile();
if (create) {
System.out.println("File creation is succesful.");
}else {
System.out.println("There is already a file by this name.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Copy after login

FileWriter in Java

Example #3

Java program to demonstrate the appending of string to the end of the file.

Code:

import java.io.*;
public class Example {
public static void append(String fileName,
String string)
{
try {
// The file is opened in append mode
BufferedWriter out1 = new BufferedWriter(
new FileWriter(fileName, true));
out1.write(string);
out1.close();
}
catch (IOException e) {
System.out.println("occurance of exception" + e);
}
}
public static void main(String[] args)
throws Exception
{
// A sample file is created with some text containing in it
String fileName = "Shobha.txt";
try {
BufferedWriter out1 = new BufferedWriter(
new FileWriter(fileName));
out1.write("Learning appending\n");
out1.close();
}
catch (IOException e) {
System.out.println("occurance of exception" + e);
}
// The newly created file is appended with the string value passed here
String string = "Learning is good";
append(fileName, string);
// contents of the modified file are printed here
try {
BufferedReader in1 = new BufferedReader(
new FileReader("Shobha.txt"));
String mystr;
while ((mystr = in1.readLine()) != null) {
System.out.println(mystr);
}
}
catch (IOException e) {
System.out.println("Occurance of exception" + e);
}
}
}
Copy after login

Output:

FileWriter in Java

Example #4

Java program using FileWriter to write to a file one line after the other.

Code:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class List {
public static void main(String[] args) throws Exception {
ArrayList<String> list1 = new ArrayList<String>();
// The newly created file is appended with the string value passed here
list1.add("Understanding an example in java");
list1.add("second line of the file");
list1.add("third line of the file");
writeFile("C:/Users/shivakumarsh/Desktop/Learning/source.txt", list1);
System.out.println("file creation is successful");
}
public static void write(String fileName, List<String> list1) throws Exception {
FileWriter fwd = null;
BufferedWriter bwd = null;
try {
fwd = new BufferedWriter(fwd);
for (int j = 0; list1 != null && j < list.size(); j++) {
bwd.write(list.get(j));
bwd.write("\n");
}
} catch (Exception e1) {
System.out.println("error occured:" + e1.getMessage());
throw e1;
} finally {
try {
bwd.close();
} catch (Exception e1) {
}
try {
fwd.close();
} catch (Exception e1) {
}
}
}
}
Copy after login

Output:

FileWriter in Java

Conclusion

In this tutorial, we understand the concept of FileWriter as in the definition of FileWriter, how to declare FileWriter, constructors in FileWriter, and programming examples to demonstrate the creation of FileWriter class, using FileWriter class to create a text file,  using FileWriter class to append text to an existing file consisting of contents, using FileWriter class to write to a new file line by line, that is adding contents one line after the other.

Recommended Article

This is a guide to FileWriter in Java. Here we discuss how to declare FileWriter, constructors in FileWriter and its methods along with code implementation. You can also go through our other suggested articles to learn more –

  1. Layout in Java
  2. Java Compilers
  3. Merge Sort In Java
  4. Java Parallel Stream

The above is the detailed content of FileWriter in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles