Java put string in file

Write Text to a File in Java

In this tutorial we are going to learn how to write text to a text file in a Java application. By different Java example programs we will explore different approaches to write a String into a text file using Java core classes.

Using Java NIO Files.write() static method

Following program to create a new file named test.txt and write text using Files.write() method.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FilesWriteExample1  public static void main(String. args)  try  String fileName = "test.txt"; Path filePath = Paths.get(fileName); String contentToAppendToFile = "Simple Solution"; // Convert String into byte array and write to file Files.write(filePath, contentToAppendToFile.getBytes(), StandardOpenOption.CREATE); > catch (IOException e)  e.printStackTrace(); > > >

By using option StandardOpenOption.APPEND we can append text to an existing file.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FilesWriteExample2  public static void main(String. args)  try  String fileName = "test.txt"; Path filePath = Paths.get(fileName); String contentToAppendToFile = "Simple Solution"; // Append to existing file. Files.write(filePath, contentToAppendToFile.getBytes(), StandardOpenOption.APPEND); > catch (IOException e)  e.printStackTrace(); > > >

The above append example will throw an error message when the file we are trying to write does not exist.

java.nio.file.NoSuchFileException: test.txt at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102) at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230) at java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:434) at java.nio.file.Files.newOutputStream(Files.java:216) at java.nio.file.Files.write(Files.java:3292) at FilesWriteExample2.main(FilesWriteExample2.java:15)

To fix this error and make the application create a new file when it doesn’t exist and append when there is a file then we can add the option StandardOpenOption.CREATE as the following example.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FilesWriteExample3  public static void main(String. args)  try  String fileName = "test.txt"; Path filePath = Paths.get(fileName); String contentToAppendToFile = "Simple Solution"; // use 2 options to create file if it doesn't exist // and append if file exist. Files.write(filePath, contentToAppendToFile.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); > catch (IOException e)  e.printStackTrace(); > > >

Files class also provides a method to allow writing a list of String.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; public class FilesWriteExample4  public static void main(String. args)  try  String fileName = "test.txt"; Path filePath = Paths.get(fileName); ListString> contentToWrite = new ArrayList<>(); contentToWrite.add("Line 1"); contentToWrite.add("Line 2"); contentToWrite.add("Line 3"); // write a list of String Files.write(filePath, contentToWrite, StandardOpenOption.CREATE, StandardOpenOption.APPEND); > catch (IOException e)  e.printStackTrace(); > > >

Using Java NIO Files.newBufferedWriter() static method

Following Java program to show how to use Files.newBufferedWriter() to open existing files for writing or creating new files for writing text.

import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FilesNewBufferedWriterExample  public static void main(String. args)  try  String fileName = "test.txt"; Path filePath = Paths.get(fileName); BufferedWriter bufferedWriter = Files.newBufferedWriter(filePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND); bufferedWriter.write("Line 1"); bufferedWriter.newLine(); bufferedWriter.write("Line 2"); bufferedWriter.newLine(); bufferedWriter.write("Line 3"); bufferedWriter.close(); > catch (IOException e)  e.printStackTrace(); > > >

Using Java IO FileWriter

import java.io.FileWriter; import java.io.IOException; public class FileWriterExample1  public static void main(String. args)  String fileName = "test.txt"; // use FileWriter to write text file try(FileWriter fileWriter = new FileWriter(fileName))  fileWriter.write("Line 1\n"); fileWriter.write("Line 2\n"); > catch (IOException e)  e.printStackTrace(); > > >

Using Java IO BufferedWriter and FileWriter

Using BufferedWriter to handle large file.

import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class FileWriterExample2  public static void main(String. args)  String fileName = "test.txt"; // use FileWriter with BufferedWriter try(FileWriter fileWriter = new FileWriter(fileName); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter))  bufferedWriter.write("Line 1"); bufferedWriter.newLine(); bufferedWriter.write("Line 2"); > catch (IOException e)  e.printStackTrace(); > > >

Using Java IO PrintWriter

import java.io.IOException; import java.io.PrintWriter; public class PrintWriterExample  public static void main(String. args)  String fileName = "test.txt"; // use PrintWriter to write text file try(PrintWriter printWriter = new PrintWriter(fileName))  printWriter.write("Line 1"); printWriter.write("\n"); printWriter.write("Line 2"); > catch (IOException e)  e.printStackTrace(); > > >

Using Java IO FileOutputStream, OutputStreamWriter and BufferedWriter

import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class BufferedWriterExample  public static void main(String. args)  String fileName = "test.txt"; try(FileOutputStream fileOutputStream = new FileOutputStream(fileName); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter))  bufferedWriter.write("Line 1"); bufferedWriter.newLine(); bufferedWriter.write("Line 2"); > catch (IOException e)  e.printStackTrace(); > > >

Источник

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.

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.

Источник

Write String to File in Java

To write String to File in Java, there are many processes we can follow. Some of them are using FileUtils class of apache’s commons.io library, Input Streams, etc.

In this tutorial, we will learn some of the ways to write string to a file using following examples.

1. Read file as string using BufferedOutputStream

In this example, we will use BufferedOutputStream as the main step to write string data to file. Following is the sequence of steps.

  1. Create file object with the path of the text file.
  2. Create a FileOutputStream with the file object created in the above step.
  3. Using this FileOutputStream, create a BufferedOutputStream.
  4. Convert data string to byte array.
  5. Use BufferedOutputStream.write() to write the byte array to file.
  6. Close BufferedOutputStream and FileOutputStream to release any system resources associated with the streams.
  7. We have the file contents read to string.

WriteStringToFile.java

import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * Java Example Program to Write String to File */ public class WriteStringToFile < public static void main(String[] args) < File file = new File("files/data1.txt"); String data = "Hello World!\nWelcome to www.tutorialkart.com"; try(FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos)) < //convert string to byte array byte[] bytes = data.getBytes(); //write byte array to file bos.write(bytes); bos.close(); fos.close(); System.out.print("Data written to file successfully."); >catch (IOException e) < e.printStackTrace(); >> >

FileOutputStream and BufferedOutputStream could throw IOException. Hence we used Java Try with Resource.

Run the program from command prompt or in your favorite IDE like Eclipse.

Data written to file successfully.

2. Write string to file using commons.io

In this example, we shall use Apache’s commons.io package to write string to file.

  1. Create file object with the path to the text file.
  2. Have your data ready in a string.
  3. Call the method FileUtils.writeStringToFile() and pass the file object, data string as arguments to it. The function writes the data to file.

WriteStringToFile.java

import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; /** * Java Example Program to Write String to File */ public class WriteStringToFile < public static void main(String[] args) < File file = new File("files/data1.txt"); String data = "Hello World!\nWelcome to www.tutorialkart.com"; try < //write string to file FileUtils.writeStringToFile(file, data); System.out.print("Data written to file successfully."); >catch (IOException e) < e.printStackTrace(); >> >

Run this program, and you will get the following output.

Data written to file successfully.

Conclusion

In this Java Tutorial, we learned how to write String to file, using inbuilt classes and some external Java packages.

Источник

Читайте также:  Меняем размер шрифта при помощи CSS
Оцените статью