Writing string to file 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

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

Читайте также:  Html absolute position top right

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.

Источник

Java 11 – Files writeString() API

Learn to write a string into file in Java using Files.writeString(path, string, options) method. This API has been introduced in Java 11.

1. Files writeString() methods

java.nio.file.Files class has two overloaded static methods to write content to file.

public static Path writeString​(Path path, CharSequence csq, OpenOption. options) throws IOException public static Path writeString​(Path path, CharSequence csq, Charset cs, OpenOption. options) throws IOException
  • First method writes all content to a file, using the UTF-8 charset.
  • First method is equivalent to writeString(path, string, StandardCharsets.UTF_8, options) .
  • Second method does the same with with only using the specified charset.
  • options specifies how the file is opened.
Читайте также:  Javascript select all rows in table

2. Files writeString() example

Java program to write String into a file using Files.writeString() method.

import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.Files; import java.io.IOException; import java.nio.file.StandardOpenOption; public class Main < public static void main(String[] args) < Path filePath = Paths.get("C:/", "temp", "test.txt"); try < //Write content to file Files.writeString(filePath, "Hello World !!", StandardOpenOption.APPEND); //Verify file content String content = Files.readString(filePath); System.out.println(content); >catch (IOException e) < e.printStackTrace(); >> >

Where the file c:/temp/test.txt is empty initially.

Drop me your questions in comments section.

Источник

Java Write String to a File

In this tutorial, we will see different ways that Java offers to write a String into a file. We’ll make use of BufferedWriter, PrintWriter, FileOutputStream, DataOutputStream, FileChannel, and Temporary File, and the advantages that each one gives us.

2. BufferedWriter Example

In this example, we will use the BufferedWriter class. The BufferedWriter class can be used to write a String to a file more efficiently. The BufferedWriter maintains an internal buffer of 8192 characters. The characters are written to an internal buffer and once the buffer is filled or the writer is closed, the string is written to the disk, reducing the usage of the disk. bufferedWriter.java

import java.io.FileWriter; import java.io.BufferedWriter; public class bufferedWriter < public static void main(String args[]) < String data = "This is the data i want to write to a file"; try < FileWriter file = new FileWriter("output.txt"); BufferedWriter buffer = new BufferedWriter(file); buffer.write(data); buffer.close(); >catch (Exception e) < e.getStackTrace(); >> >

java write string to file - File Created with the BufferedWriter Example.

3. PrintWriter Example

This class implements all of the print methods found in PrintStream . Methods in this class never throw I/O exceptions, although some of its constructors may. PrintWriter class write formatted representations of objects to a text-output stream. Is usually the fastest and easiest way to write String data to a file.

import java.io.PrintWriter; class printWriter < public static void main(String[] args) < String data = "This is the data i want to write to a file."; try < PrintWriter output = new PrintWriter("output2.txt"); output.println(data); output.close(); >catch (Exception e) < e.getStackTrace(); >> >

java write string to file - File Created with the PrintWriter Example

4. FileOutputStream Example

A FileOutputStream is an output stream for writing data to a File or to a FileDescriptor . FileOutputStream is meant for writing streams of raw bytes such as image data. fileoutputStream.java

import java.io.FileOutputStream; public class fileoutputStream < public static void main(String[] args) < String data = "This is the data i want to write to a file"; try < FileOutputStream output = new FileOutputStream("output3.txt"); byte[] array = data.getBytes(); output.write(array); output.close(); >catch (Exception e) < e.getStackTrace(); >> >

java write string to file - File Created with the FileOutputStream Example.

5. DataOutputStream Example

DataOutputStream let us write primitive Java data types to an output stream. We can then use a DataInputStream to read the data back in. dataoutputStream.java

import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; class dataoutputStream < public static void main(String args[]) throws IOException < try (DataOutputStream out = new DataOutputStream(new FileOutputStream("output4.txt"))) < out.writeDouble(5.5); out.writeInt(100); out.writeBoolean(false); out.writeChar('C'); >catch (FileNotFoundException ex) < System.out.println("Cannot Open Output File"); return; >try (DataInputStream in = new DataInputStream(new FileInputStream("output4.txt"))) < double a = in.readDouble(); int b = in.readInt(); boolean c = in.readBoolean(); char d = in.readChar(); System.out.println("Values: " + a + " " + b + " " + c + " " + d); >catch (FileNotFoundException e) < System.out.println("Cannot Open the Input File"); return; >> >

Fig. 4: File Created with DataOutputStream Example and the Data Inside it.

6. FileChannel Example

With FileChannel class we are able to read, write, map, and manipulate a file. It has a current position within its file which can be both queried and modified. The size of the file increases when bytes are written beyond its current size and also decreases when it is truncated. fileChannel.java

import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.*; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; public class fileChannel < public static void main(String[] args) throws IOException < try < RandomAccessFile file = new RandomAccessFile("output5.txt", "rw"); FileChannel channel = file.getChannel(); String s = "This is the data i want to write to a file"; ByteBuffer buf = ByteBuffer.allocate(48); buf.put(s.getBytes()); buf.flip(); channel.write(buf); buf.clear(); channel.read(buf); String read = new String(buf.array(), StandardCharsets.UTF_8); System.out.println(read); >catch (FileNotFoundException e) < // TODO Auto-generated catch block e.printStackTrace(); >> >

Fig. 5: The Data we Wrote in the Output File.

7. File Class Example with Temporary File

The temporary file is just a regular file created on a predefined directory. The File class give us methods that help us create, delete, write and get its different properties. tempFile.java

import java.io.File; import java.io.IOException; public class tempFile < public static void main(String[] args) throws IOException < File file = File.createTempFile("random", "txt"); System.out.println("File name : " + file.getName()); System.out.println("Path : " + file.getPath()); System.out.println("Absolute path : " + file.getAbsolutePath()); System.out.println("Parent : " + file.getParent()); System.out.println("Exists : " + file.exists()); if (file.exists()) < System.out.println("Is writeable : " + file.canWrite()); System.out.println("Is readable : " + file.canRead()); System.out.println("Is a directory : " + file.isDirectory()); System.out.println("File Size in bytes : " + file.length()); >file.deleteOnExit(); > >

8. Summary

In these examples we learnt about different ways we can create, write, modify, parse files in Java. Depending on the application we want to create, we can choose a specific class that will provide us with flexibility and efficiency.

Читайте также:  Telegram bot command java

9. Download the source code

This was an example of how to create,write and read files in Java!

Источник

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