search
HomeJavajavaTutorialFileWriter in Java
FileWriter in JavaAug 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

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();
}
}

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();
}
}
}

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);
}
}
}

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 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172500344564251.png?x-oss-process=image/resize,p_40" class="lazy" alt="FileWriter in Java" ></p>
<h3 id="Conclusion">Conclusion</h3>
<p>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.</p>
<h3 id="Recommended-Article">Recommended Article</h3>
<p>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 –</p>
<ol>
<li>Layout in Java</li>
<li>Java Compilers</li>
<li>Merge Sort In Java</li>
<li>Java Parallel Stream</li>
</ol></string></string></string>

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

Statement
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
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools