Java filewriter not flushing

Java filewriter not flushing

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

FileWriter flush() Method in Java

In this tutorial, we will learn about the flush() method of FileWriter class in Java. This method is used to flush the writer, which means that this method will remove all the data present inside the writer. It neither accepts any parameter nor returns any value.

Syntax

This is the syntax declaration of the flush() method, this method does not take any parameter as input and does not return anything as its return type is void.

Example1: FileWriter flush()

In the following example, we are implementing how the flush() method works, this method is used to remove the written data from the writer, here we have written the data to the writer and after that, we are flushing it by calling the flush() method.

import java.io.FileWriter; import java.io.IOException; class StudyTonight < public static void main(String[] args) throws IOException < try < FileWriter fileWriter=new FileWriter("E:\\studytonight\\output.txt"); String str = "Hello Studytonight"; fileWriter.write(str); fileWriter.flush(); fileWriter.close(); System.out.println("Data Written to the file successfully"); >catch(Exception e) < System.out.println("Error: "+e.toString()); >> >

Data Written to the file successfully

Example 2: FileWriter flush()

Here, we are implementing the example of a flush() method to clear the writer. Once we have written the data into it we call the flush method. This method is used to flush the writer, which means that this method will remove all the data present inside the writer.

import java.io.FileWriter; import java.io.IOException; class StudyTonight < public static void main(String[] args) throws IOException < try < FileWriter fileWriter=new FileWriter("E:\\studytonight\\output.txt"); char c='A'; fileWriter.write(c); fileWriter.flush(); fileWriter.close(); System.out.println("Data Written to the file successfully"); >catch(Exception e) < System.out.println("Error: "+e.toString()); >> >

Data Written to the file successfully

Читайте также:  Java current version check

Conclusion

In this tutorial, we learned about the flush() method of FileWriter class in Java. This method is used to flush the writer, which means that this method will remove all the data present inside the writer. It neither accepts any parameter nor returns any value.

Источник

Class FileWriter

Writes text to character files using a default buffer size. Encoding from characters to bytes uses either a specified charset or the platform’s default charset.

Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.

The FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream .

Field Summary

Fields declared in class java.io.Writer

Constructor Summary

Constructs a FileWriter given the File to write and a boolean indicating whether to append the data written, using the platform’s default charset.

Constructs a FileWriter given the File to write, charset and a boolean indicating whether to append the data written.

Constructs a FileWriter given a file name and a boolean indicating whether to append the data written, using the platform’s default charset.

Constructs a FileWriter given a file name, charset and a boolean indicating whether to append the data written.

Method Summary

Methods declared in class java.io.OutputStreamWriter

Methods declared in class java.io.Writer

Methods declared in class java.lang.Object

Constructor Details

FileWriter

FileWriter

Constructs a FileWriter given a file name and a boolean indicating whether to append the data written, using the platform’s default charset.

FileWriter

FileWriter

Constructs a FileWriter given the File to write and a boolean indicating whether to append the data written, using the platform’s default charset.

FileWriter

FileWriter

FileWriter

Constructs a FileWriter given a file name, charset and a boolean indicating whether to append the data written.

FileWriter

FileWriter

Constructs a FileWriter given the File to write, charset and a boolean indicating whether to append the data written.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java FileWriter Example

Java FileWriter Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java FileWriter

  • Java FileWriter class is a part of java.io package.
  • FileWriter is a sub class of java.io.OutputStreamWriter class.
  • FileWriter is meant for writing streams of characters.
  • FileWriter is used to write to character files. Its write() methods allow you to write character(s) or strings to a file.
  • FileWriters are usually wrapped by higher-level Writer objects, such as BufferedWriter or PrintWriter , which provide better performance and higher-level, more flexible methods to write data.
Читайте также:  Html document что это

Java FileWriter

FileWriter Constructors

  1. FileWriter(File file) : Creates a FileWriter object using specified File object. It throws an IOException if the file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.
  2. FileWriter(File file, boolean append) : Creates a FileWriter object using specified File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. It throws an IOException if the file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.
  3. FileWriter(FileDescriptor fd) : Creates a FileWriter object associated with specified file descriptor.
  4. FileWriter(String fileName) : Creates a FileWriter object using specified fileName. It throws an IOException if the named file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.
  5. FileWriter(String fileName, boolean append) : Creates a FileWriter object using specified fileName with a boolean indicating whether or not to append the data written. If the second argument is true, then the data will be written to the end of the file rather than the beginning. It throws an IOException if the named file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.

Java FileWriter Example

FileWriter inherits the method of java.io.OutputStreamWriter and java.io.Writer classes. Let’s have a look at the below methods with examples.

write(int c)

This method writes a single character specified by int c.

package com.journaldev.io.filewriter; import java.io.FileWriter; import java.io.IOException; /** * Java write file using FileWriter write method * * @author pankaj * */ public class FileWriterWriteIntExample < public static void main(String[] args) < FileWriter fileWriter = null; try < fileWriter = new FileWriter("D:/data/file.txt"); //inherited method from java.io.OutputStreamWriter fileWriter.write(65); fileWriter.write(66); fileWriter.write(67); >catch (Exception e) < e.printStackTrace(); >finally < try < if (fileWriter != null) < fileWriter.flush(); fileWriter.close(); >> catch (IOException e) < e.printStackTrace(); >> > > 

Java FileWriter Example

FileWriter implements AutoCloseable interface, hence we can use try with resources while using FileWriter class.

package com.journaldev.io.filewriter; import java.io.FileWriter; /** * Java write file using FileWriter write method using try with resource * * @author pankaj * */ public class FileWriterWriteIntTryWithResource < public static void main(String[] args) < try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) < //inherited method from java.io.OutputStreamWriter fileWriter.write(65); fileWriter.write(66); fileWriter.write(67); >catch (Exception e) < e.printStackTrace(); >> > 

Note: In the above program fileWriter.write(65) will write A into file because the 65 is the decimal value for the character A, hence integer 65 will be converted into character A and same for the other.

write(String str, int off, int len)

This method writes a portion of String str from int off to int len .

  • str: String to be written
  • off: Offset from which to start reading characters
  • len: Number of characters to be written

If the value of the len parameter is negative then no characters are written.

package com.journaldev.io.filewriter; import java.io.FileWriter; /** * Java write file using FileWriter write(String s, int off, int len) method * * @author pankaj * */ public class FileWriterWriteStringExample < public static void main(String[] args) < String data = "This is FileWriter Example."; try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) < //inherited method from java.io.OutputStreamWriter fileWriter.write(data, 8, 10); >catch (Exception e) < e.printStackTrace(); >> > 

FileWriter write example

write(char[] cbuf, int off, int len)

This method writes a portion of an array of characters specified by char[] cbuf from int off to int len .

  • cbuf: A character array
  • off: Offset from which to start reading characters
  • len : Number of characters to write
package com.journaldev.io.filewriter; import java.io.FileWriter; /** * Java write file using FileWriter write(char[] cbuf, int off, int len) method * * @author pankaj * */ public class FileWriterWriteCharArray < public static void main(String[] args) < char[] data = "This is FileWriter Example.".toCharArray(); try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) < //inherited method from java.io.OutputStreamWriter fileWriter.write(data, 8, 10); >catch (Exception e) < e.printStackTrace(); >> > 

write(char[] cbuf)

This method writes the array of character specified by cbuf.

package com.journaldev.io.filewriter; import java.io.FileWriter; /** * Java write file using FileWriter write(char[] cbuf) method * * @author pankaj * */ public class FileWriterWriteCharArrayExample < public static void main(String[] args) < char[] data = "This is FileWriter Example.".toCharArray(); try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) < //inherited method from java.io.Writer fileWriter.write(data); >catch (Exception e) < e.printStackTrace(); >> > 

write(String str)

This method writes a string value into file specified by str .

package com.journaldev.io.filewriter; import java.io.FileWriter; /** * Java write file using FileWriter write(String str) method * * @author pankaj * */ public class FileWriterWriteString < public static void main(String[] args) < try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) < //inherited method from java.io.Writer fileWriter.write("JournalDev"); >catch (Exception e) < e.printStackTrace(); >> > 

append(char c)

This method appends the specified character to this writer where c is the 16-bit character to append.

package com.journaldev.io.filewriter; import java.io.FileWriter; /** * Java write file using FileWriter append(char c) method * * @author pankaj * */ public class FileWriterAppendCharacter < public static void main(String[] args) < try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) < //inherited method from java.io.Writer fileWriter.write("JournalDev"); fileWriter.append('C'); >catch (Exception e) < e.printStackTrace(); >> > 

flush()

This method flushes the stream. When flush() method is called it immediately writes the data to the output file.

package com.journaldev.io.filewriter; import java.io.FileWriter; /** * Java write file with FileWriter flush() method * * @author pankaj * */ public class FileWriterFlushExample < public static void main(String[] args) < try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) < //inherited method from java.io.Writer fileWriter.write("JournalDev"); //inherited method from java.io.OutputStreamWriter fileWriter.flush(); fileWriter.write(" Tutorials"); fileWriter.flush(); >catch (Exception e) < e.printStackTrace(); >> > 

close()

This method flush the stream before close it. Once the stream has been closed, invocation of write() or flush() method will cause an IOException to be thrown. Closing a previously closed stream has no effect.

package com.journaldev.io.filewriter; import java.io.FileWriter; /** * Java write file with FileWriter close() method * * @author pankaj * */ public class FileWriterCloseExample < public static void main(String[] args) < try(FileWriter fileWriter = new FileWriter("D:/data/file.txt")) < //inherited method from java.io.Writer fileWriter.write("JournalDev"); //inherited method from java.io.OutputStreamWriter fileWriter.close();; fileWriter.write(" Tutorials"); >catch (Exception e) < e.printStackTrace(); >> > 
java.io.IOException: Stream closed at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source) at sun.nio.cs.StreamEncoder.write(Unknown Source) at sun.nio.cs.StreamEncoder.write(Unknown Source) at java.io.OutputStreamWriter.write(Unknown Source) at java.io.Writer.write(Unknown Source) at com.journaldev.examples.FileWriterCloseExample.main(FileWriterCloseExample.java:20) 

FileWriter vs FileOutputStream

  • FileWriter is meant for writing streams of characters while FileOutputStream is used for writing streams of raw bytes.
  • FileWriter deal with 16-bit characters while FileOutputStream deals with 8-bit bytes.
  • FileWriter can handle Unicode strings while FileOutputStream writes bytes to a file and do not accepts characters or strings hence it needs to wrapped up by OutputStreamWriter to accept strings.
Читайте также:  Php chat room scripts

Also check java write file for more about how to write file in java. That’s all for Java FileWriter, I hope nothing important got missed here.

You can download all the examples code from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью