Java add line to file

Как добавить текст в файл на Java

В этой статье показано, как включить режим добавления в следующих API-интерфейсах – Files.write, Files.WriteString и FileWriter.

В этой статье показано, как использовать следующие API Java для добавления текста в конец файла.

  1. Файлы.запись – Добавьте одну строку в файл, Java 7.
  2. – Добавьте одну строку в файл, Java 7. – Добавьте несколько строк в файл, Java 7, Java 8.
  3. Файлы.Запись – Ява 11.
  4. Файлообменник
  5. Поток вывода файла
  6. Файлы/| – Apache Commons IO.

В Java для API-интерфейсов NIO, таких как Files.write , мы можем использовать StandardOpenOption. ДОБАВЬТЕ , чтобы включить режим добавления. Для примеров:

// append a string to the end of the file private static void appendToFile(Path path, String content) throws IOException

Для классических API ввода-вывода, таких как файловый редактор или |/Поток вывода файла , мы можем передать true во второй аргумент конструктора, чтобы включить режим добавления. Для примеров:

// append to the file try (FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw)) < bw.write(content); bw.newLine(); >// append to the file try (FileOutputStream fos = new FileOutputStream(file, true))

1. Добавьте одну строку в файл – Files.write

Если файл не существует, API выдает исключение NoSuchFileException

Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);

Лучшее решение всегда сочетает в себе стандартную опцию. СОЗДАТЬ и Стандартная опция. ДОБАВЛЯТЬ . Если файл не существует, API создаст и запишет текст в файл; если файл существует, добавьте текст в конец файла.

Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.APPEND);

1.1 В приведенном ниже примере показано, как добавить одну строку в конец файла.

package com.mkyong.io.file; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FileAppend1 < private static final String NEW_LINE = System.lineSeparator(); public static void main(String[] args) throws IOException < Path path = Paths.get("/home/mkyong/test/abc.txt"); appendToFile(path, "hello world" + NEW_LINE); >// Java 7 private static void appendToFile(Path path, String content) throws IOException < // if file not exists throws java.nio.file.NoSuchFileException /* Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);*/ // if file not exists, create and write to it // otherwise append to the end of the file Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.APPEND); >>

2. Добавление нескольких строк в файл – Добавление нескольких строк в файл –

Files.write также поддерживает Повторяющийся интерфейс для нескольких строк, мы можем добавить Список в файл.

// append lines of text private static void appendToFileJava8(Path path, List list) throws IOException < // Java 7? /*Files.write(path, list, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);*/ // Java 8, default utf_8 Files.write(path, list, StandardOpenOption.CREATE, StandardOpenOption.APPEND); >

3. Java 11 – Файлы.запись в режиме добавления.

В Java 7 нам нужно преобразовать Строку в байт[] и записать или добавить его в файл.

String content = ". "; Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.APPEND);

В Java 11 мы можем использовать новый Files.WriteString API для записи или добавления строки непосредственно в файл. Режим добавления работает таким же образом.

// Java 11, writeString, append mode private static void appendToFileJava11(Path path, String content) throws IOException < // utf_8 /*Files.writeString(path, content, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);*/ // default StandardCharsets.UTF_8 Files.writeString(path, content, StandardOpenOption.CREATE, StandardOpenOption.APPEND); >

4. Файлообменник

Для устаревших API ввода-вывода, таких как FileWriter , второй аргумент конструктора указывает режим добавления.

// append // if file not exists, create and write // if the file exists, append to the end of the file try (FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw)) < bw.write(content); bw.newLine(); // add new line, System.lineSeparator() >

4.1 В приведенном ниже примере показано, как использовать файловый редактор для добавления одной строки в конец файла.

package com.mkyong.io.file; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileAppend4 < public static void main(String[] args) throws IOException < File file = new File("/home/mkyong/test/abc.txt"); appendToFileFileWriter(file, "hello world"); System.out.println("Done"); >private static void appendToFileFileWriter(File file, String content) throws IOException < // default - create and write // if file not exists, create and write // if file exists, truncate and write /*try (FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw)) < bw.write(content); bw.newLine(); >*/ // append mode // if file not exists, create and write // if file exists, append to the end of the file try (FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw)) < bw.write(content); bw.newLine(); // add new line, System.lineSeparator() >> >

4.2 Приведенный ниже пример добавляет Список или несколько строк в конец файла.

private static void appendToFileFileWriter( File file, List content) throws IOException < try (FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw)) < for (String s : content) < bw.write(s); bw.newLine(); >> > 

5. Поток вывода файла

Режим добавления FileOutputStream работает так же, как и Файловая программа .

private static void appendToFileFileOutputStream(File file, String content) throws IOException < // append mode try (FileOutputStream fos = new FileOutputStream(file, true)) < fos.write(content.getBytes(StandardCharsets.UTF_8)); >>

6. Файлы

В приведенном ниже примере используется популярный Apache commons-io Файлы.writeStringToFile для добавления строки в конец файла.

import org.apache.commons.io.FileUtils; private static void appendToFileFileUtils(File file, String content) throws IOException < // append mode FileUtils.writeStringToFile( file, content, StandardCharsets.UTF_8, true); >

Просмотрите файлы .writeStringToFile подпись; последний или четвертый аргумент указывает режим добавления.

public static void writeStringToFile(final File file, final String data, final Charset charset,final boolean append) throws IOException < try (OutputStream out = openOutputStream(file, append)) < IOUtils.write(data, out, charset); >>

7. В старые добрые времена.

До Java 7 мы могли использовать файловый редактор для добавления текста в файл и закрытия ресурсов вручную.

package com.mkyong; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class ClassicBufferedWriterExample < public static void main(String[] args) < BufferedWriter bw = null; FileWriter fw = null; try < String content = "Hello"; fw = new FileWriter("app.log", true); bw = new BufferedWriter(fw); bw.write(content); >catch (IOException e) < System.err.format("IOException: %s%n", e); >finally < try < if (bw != null) bw.close(); if (fw != null) fw.close(); >catch (IOException ex) < System.err.format("IOException: %s%n", ex); >> > >

P.S. Приведенный выше код предназначен только для развлечения и устаревших целей, всегда придерживается метода “попробуй с ресурсами”, чтобы закрыть ресурсы.

Рекомендации

Читайте ещё по теме:

Источник

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.

Источник

Appending to a File in Java

Learn to append the data to a file in Java using BufferedWritter, PrintWriter, FileOutputStream and Files classes. In all the examples, while opening the file to write, we have passed a second argument as true which denotes that the file needs to be opened in append mode.

With Files class, we can write a file using it’s write() function. Internally write() function uses OutputStream to write byte array into the file.

To append content to an existing file, Use StandardOpenOption.APPEND while writing the content.

String textToAppend = "Happy Learning !!"; Path path = Paths.get("c:/temp/samplefile.txt"); Files.write(path, textToAppend.getBytes(), StandardOpenOption.APPEND); 

BufferedWriter buffers the data in an internal byte array before writing to the file, so it results in fewer IO operations and improves the performance.

To append a string to an existing file, open the writer in append mode and pass the second argument as true .

String textToAppend = "Happy Learning !!"; Strinng filePath = "c:/temp/samplefile.txt"; try(FileWriter fw = new FileWriter(filePath, true); BufferedWriter writer = new BufferedWriter(fw);)

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

To append content to an existing file, open the writer in append mode by passing the second argument as true .

String textToAppend = "Happy Learning !!"; String fileName = "c:/temp/samplefile.txt"; try(FileWriter fileWriter = new FileWriter(fileName, true); 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 .

To append content to an existing file, open FileOutputStream in append mode by passing the second argument as true .

String textToAppend = "\r\n Happy Learning !!"; String fileName = "c:/temp/samplefile.txt"; try(FileOutputStream outputStream = new FileOutputStream(fileName, true))

Источник

Читайте также:  Php настройки для bitrix
Оцените статью