Writing to text files in java

Writing to a File in Java

When working on an enterprise application, sometimes it is needed to write the text or binary data into files in Java e.g. writing user-generated reports into the filesystem.

Though there are multiple ways of writing the files in Java, let’s quickly go through a few of them for quick reference when it is needed.

1. Using Files.writeString() and Files.write()

With the method writeString() introduced in Java 11, we can write a String into a file using a single-line statement.

  • As the name suggests, writeString() method is used to write the character data into files.
  • All characters are written as they are, including the line separators. No extra characters are added.
  • By default, UTF-8 character encoding is used.
  • It throws IOException if an I/O error occurs writing to or creating the file, or the text cannot be encoded using the specified charset.
Path filePath = Path.of("demo.txt"); String content = "hello world !!"; Files.writeString(filePath, content);

Files class another method write() since Java 7 and it works similar to writeString(). The write() method can be used to write the raw data in bytes or to write the strings in lines.

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; //Write bytes Files.write(filePath, content.getBytes()); //Write lines List lines = Arrays.asList("a", "b", "c"); Files.write(filePath, lines, StandardCharsets.UTF_8);

2. Fast Writing FileChannel and ByteBuffer

Читайте также:  Button click java swing

FileChannel can be used for reading, writing, mapping, and manipulating a file. If we are writing the large files, FileChannel can be faster than standard IO.

File channels are safe for use by multiple concurrent threads.

Path fileName = Path.of("demo.txt"); String content = "hello world !!"; try ( RandomAccessFile stream = new RandomAccessFile(filePath.toFile(),"rw"); FileChannel channel = stream.getChannel();)

BufferedWriter the simplest way to write the content to a file. It writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriter and OutputStreamWriter .

As it buffers before writing, so it results in fewer IO operations, so it improves the performance.

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try (BufferedWriter writer = new BufferedWriter( new FileWriter(filePath.toFile())))

4. Using FileWriter or PrintWriter

FileWriter the most clean way to write files. The syntax is self-explanatory and easy to read and understand. FileWriter writes directly into the file (less performance) and should be used only when the number of writes is less.

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try(FileWriter fileWriter = new FileWriter(filePath.toFile()))

Use PrintWriter to write formatted text to a file. This class implements all of the print methods found in PrintStream , so you can use all formats which you use with System.out.println() statements.

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try(FileWriter fileWriter = new FileWriter(filePath.toFile()); PrintWriter printWriter = new PrintWriter(fileWriter);)

Use FileOutputStream to write binary data to a file. FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter .

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try(FileOutputStream outputStream = new FileOutputStream(filePath.toFile()))

DataOutputStream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try ( FileOutputStream outputStream = new FileOutputStream(filePath.toFile()); DataOutputStream dataOutStream = new DataOutputStream(new BufferedOutputStream(outputStream));)
  1. If we try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown (except using Path method).
  2. Always close the output stream after writing the file content to release all resources. It will also help in not corrupting the file.
  3. Use PrintWriter is used to write formatted text.
  4. Use FileOutputStream to write binary data.
  5. Use DataOutputStream to write primitive data types.
  6. Use FileChannel to write larger files. It is the preferred way of writing filesin Java 8 as well.

Источник

How to Read and Write Text File in Java

In this tutorial, we show you how to read from and write to text (or character) files using classes available in the java.io package. First, let’s look at the different classes that are capable of reading and writing character streams.

1. Reader, InputStreamReader, FileReader and BufferedReader

Reader is the abstract class for reading character streams. It implements the following fundamental methods:

  • read() : reads a single character.
  • read(char[]) : reads an array of characters.
  • skip(long) : skips some characters.
  • close() : closes the stream.

FileReader is a convenient class for reading text files using the default character encoding of the operating system.

BufferedReader reads text from a character stream with efficiency (characters are buffered to avoid frequently reading from the underlying stream) and provides a convenient method for reading a line of text readLine() .

The following diagram show relationship of these reader classes in the java.io package:

Reader Hierarchy

2. Writer, OutputStreamWriter, FileWriter and BufferedWriter

Writer is the abstract class for writing character streams. It implements the following fundamental methods:

  • write(int) : writes a single character.
  • write(char[]) : writes an array of characters.
  • write(String) : writes a string.
  • close() : closes the stream.

FileWriter is a convenient class for writing text files using the default character encoding of the operating system.

BufferedWriter writes text to a character stream with efficiency (characters, arrays and strings are buffered to avoid frequently writing to the underlying stream) and provides a convenient method for writing a line separator: newLine() .

The following diagram show relationship of these writer classes in the java.io package:

Writer Hierarchy

3. Character Encoding and Charset

When constructing a reader or writer object, the default character encoding of the operating system is used (e.g. Cp1252 on Windows):

FileReader reader = new FileReader("MyFile.txt"); FileWriter writer = new FileWriter("YourFile.txt");

So if we want to use a specific charset, use an InputStreamReader or OutputStreamWriter instead. For example:

InputStreamReader reader = new InputStreamReader( new FileInputStream("MyFile.txt"), "UTF-16");

And the following statement constructs a writer with the UTF-8 encoding:

OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("YourFile.txt"), "UTF-8");

In case we want to use a BufferedReader , just wrap the InputStreamReader inside, for example:

InputStreamReader reader = new InputStreamReader( new FileInputStream("MyFile.txt"), "UTF-16"); BufferedReader bufReader = new BufferedReader(reader);
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("YourFile.txt"), "UTF-8"); BufferedWriter bufWriter = new BufferedWriter(writer);

4. Java Reading from Text File Example

The following small program reads every single character from the file MyFile.txt and prints all the characters to the output console:

package net.codejava.io; import java.io.FileReader; import java.io.IOException; /** * This program demonstrates how to read characters from a text file. * @author www.codejava.net * */ public class TextFileReadingExample1 < public static void main(String[] args) < try < FileReader reader = new FileReader("MyFile.txt"); int character; while ((character = reader.read()) != -1) < System.out.print((char) character); >reader.close(); > catch (IOException e) < e.printStackTrace(); >> >
package net.codejava.io; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; /** * This program demonstrates how to read characters from a text file using * a specified charset. * @author www.codejava.net * */ public class TextFileReadingExample2 < public static void main(String[] args) < try < FileInputStream inputStream = new FileInputStream("MyFile.txt"); InputStreamReader reader = new InputStreamReader(inputStream, "UTF-16"); int character; while ((character = reader.read()) != -1) < System.out.print((char) character); >reader.close(); > catch (IOException e) < e.printStackTrace(); >> >

And the following example uses a BufferedReader to read a text file line by line (this is the most efficient and preferred way):

package net.codejava.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * This program demonstrates how to read characters from a text file * using a BufferedReader for efficiency. * @author www.codejava.net * */ public class TextFileReadingExample3 < public static void main(String[] args) < try < FileReader reader = new FileReader("MyFile.txt"); BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) < System.out.println(line); >reader.close(); > catch (IOException e) < e.printStackTrace(); >> >

5. Java Writing to Text File Example

In the following example, a FileWriter is used to write two words “Hello World” and “Good Bye!” to a file named MyFile.txt :

package net.codejava.io; import java.io.FileWriter; import java.io.IOException; /** * This program demonstrates how to write characters to a text file. * @author www.codejava.net * */ public class TextFileWritingExample1 < public static void main(String[] args) < try < FileWriter writer = new FileWriter("MyFile.txt", true); writer.write("Hello World"); writer.write("\r\n"); // write new line writer.write("Good Bye!"); writer.close(); >catch (IOException e) < e.printStackTrace(); >> >

Note that, a writer uses default character encoding of the operating system by default. It also creates a new file if not exits, or overwrites the existing one. If you want to append text to an existing file, pass a boolean flag of true to constructor of the writer class:

FileWriter writer = new FileWriter("MyFile.txt", true);

The following example uses a BufferedReader that wraps a FileReader to append text to an existing file:

package net.codejava.io; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; /** * This program demonstrates how to write characters to a text file * using a BufferedReader for efficiency. * @author www.codejava.net * */ public class TextFileWritingExample2 < public static void main(String[] args) < try < FileWriter writer = new FileWriter("MyFile.txt", true); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write("Hello World"); bufferedWriter.newLine(); bufferedWriter.write("See You Again!"); bufferedWriter.close(); >catch (IOException e) < e.printStackTrace(); >> >

This is the preferred way to write to text file because the BufferedReader provides efficient way for writing character streams.

And the following example specifies specific character encoding (UTF-16) when writing to the file:

package net.codejava.io; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; /** * This program demonstrates how to write characters to a text file using * a specified charset. * @author www.codejava.net * */ public class TextFileWritingExample3 < public static void main(String[] args) < try < FileOutputStream outputStream = new FileOutputStream("MyFile.txt"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-16"); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); bufferedWriter.write("Xin chào"); bufferedWriter.newLine(); bufferedWriter.write("Hẹn gặp lại!"); bufferedWriter.close(); >catch (IOException e) < e.printStackTrace(); >> >

NOTE: From Java 7, you can use try-with-resources statement to simplify the code of opening and closing the reader/writer. For example:

try (FileReader reader = new FileReader(«MyFile.txt»)) < int character; while ((character = reader.read()) != -1) < System.out.print((char) character); >> catch (IOException e)

References:

Other Java File IO Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

Java Create and Write To Files

To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try. catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):

Example

import java.io.File; // Import the File class import java.io.IOException; // Import the IOException class to handle errors public class CreateFile < public static void main(String[] args) < try < File myObj = new File("filename.txt"); if (myObj.createNewFile()) < System.out.println("File created: " + myObj.getName()); >else < System.out.println("File already exists."); >> catch (IOException e) < System.out.println("An error occurred."); e.printStackTrace(); >> > 

To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the » \ » character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt

Example

File myObj = new File("C:\\Users\\MyName\\filename.txt"); 

Write To a File

In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method:

Example

import java.io.FileWriter; // Import the FileWriter class import java.io.IOException; // Import the IOException class to handle errors public class WriteToFile < public static void main(String[] args) < try < FileWriter myWriter = new FileWriter("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!"); myWriter.close(); System.out.println("Successfully wrote to the file."); >catch (IOException e) < System.out.println("An error occurred."); e.printStackTrace(); >> > 

To read the file above, go to the Java Read Files chapter.

Источник

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