Java adding text to file

Java adding text to file

  • 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
Читайте также:  Проверка является ли символ числом python

Источник

How to append text to a file in Java

In this quick article, I’ll show you how to append text to an existing file using Java legacy I/O API as well as non-blocking new I/O API (NIO).

The simplest and most straightforward way of appending text to an existing file is to use the Files.write() static method. This method is a part of Java’s new I/O API (classes in java.nio.* package) and requires Java 7 or higher. Here is an example that uses Files.write() to append data to a file:

try  // append data to a file Files.write(Paths.get("output.txt"), "Hey, there!".getBytes(), StandardOpenOption.APPEND); > catch (IOException ex)  ex.printStackTrace(); > 

The above code will append Hey, there! to a file called output.txt . If the file doesn’t exist, it will throw a NoSuchFileException exception. It also doesn’t append a new line automatically which is often required when appending to a text file. If you want to create a new file if it doesn’t already exist and also append new line automatically, use another variant of Files.write() as shown below:

try  // data to append ListString> contents = Arrays.asList("Hey, there!", "What's up?"); // append data to a file Files.write(Paths.get("output.txt"), contents, StandardOpenOption.CREATE, StandardOpenOption.APPEND); > catch (IOException ex)  ex.printStackTrace(); > 

If the file has encoding other than the default character encoding of the operating system, you can specify it like below:

Files.write(Paths.get("output.txt"), contents, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); 

Note: Files.write() is good if you want to append to a file once or a few times only. Because it opens and writes the file every time to the disk, which is a slow operation. For frequent append requests, you should rather BufferedWriter (explained below).

The BufferedWriter class is a part of Java legacy I/O API that can also be used to append text to a file. Here is an example that uses the Files.newBufferedWriter() static method to create a new writer (require Java 8+):

try  // create a writer BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), StandardOpenOption.APPEND); // append text to file bw.write("Hey, there!"); bw.newLine(); bw.write("What's up?"); // close the writer bw.close(); > catch (IOException ex)  ex.printStackTrace(); > 

The above code will append text to file. If the file doesn’t already exist, it will throw a NoSuchFileException exception. However, you can change it to create a new file if not available with the following:

BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), StandardOpenOption.CREATE, StandardOpenOption.APPEND); 
BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); 

If you are using Java 7 or below, you can use FileWriter wrapped in a BufferedWriter object to append data to a file as shown below:

try  // create a writer BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt", true)); // append text to file bw.write("Hey, there!"); bw.newLine(); bw.write("What's up?"); // close the writer bw.close(); > catch (IOException ex)  ex.printStackTrace(); > 

The second argument to the FileWriter constructor will tell it to append data to the file, rather than writing a new file. If the file does not already exist, it will be created.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

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

Источник

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