Java filewriter write line

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

Источник

How to Write a File Line by Line in Java?

This post summarizes the classes that can be used to write a file.

1. FileOutputStream

public static void writeFile1() throws IOException { File fout = new File("out.txt"); FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); for (int i = 0; i  10; i++) { bw.write("something"); bw.newLine(); } bw.close(); }

This example use FileOutputStream, instead you can use FileWriter or PrintWriter which is normally good enough for a text file operations.

2. FileWriter

public static void writeFile2() throws IOException { FileWriter fw = new FileWriter("out.txt"); for (int i = 0; i  10; i++) { fw.write("something"); } fw.close(); }

3. PrintWriter

public static void writeFile3() throws IOException { PrintWriter pw = new PrintWriter(new FileWriter("out.txt")); for (int i = 0; i  10; i++) { pw.write("something"); } pw.close(); }

4. OutputStreamWriter

public static void writeFile4() throws IOException { File fout = new File("out.txt"); FileOutputStream fos = new FileOutputStream(fout); OutputStreamWriter osw = new OutputStreamWriter(fos); for (int i = 0; i  10; i++) { osw.write("something"); } osw.close(); }

5. Their Differences

FileWriter is a convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

PrintWriter prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

The main difference is that PrintWriter offers some additional methods for formatting such as println and printf. In addition, FileWriter throws IOException in case of any I/O failure. PrintWriter methods do not throws IOException, instead they set a boolean flag which can be obtained using checkError(). PrintWriter automatically invokes flush after every byte of data is written. In case of FileWriter, caller has to take care of invoking flush.

If you want someone to read your code, please put the code inside

 and 

tags. For example:

Источник

Руководство Java FileWriter

Следуйте за нами на нашей фан-странице, чтобы получать уведомления каждый раз, когда появляются новые статьи. Facebook

1- FileWriter

FileWriter — это подкласс OutputStreamWriter, используемый для записи текстовых файлов.

FileWriter не имеет других методов, кроме тех, которые унаследованы от OutputStreamWriter. На самом деле вы можете использовать OutputStreamWriter для записи символов для любой цели. Однако FileWriter специально разработан для записи символов в системный файл.

 FileWriter​(File file) FileWriter​(FileDescriptor fd) FileWriter​(File file, boolean append) FileWriter​(File file, Charset charset) FileWriter​(File file, Charset charset, boolean append) FileWriter​(String fileName) FileWriter​(String fileName, boolean append) FileWriter​(String fileName, Charset charset) FileWriter​(String fileName, Charset charset, boolean append) 

Примечание: Конструкторы с параметром Charset были добавлены в FileWriter, начиная с версии Java 11. Поэтому, если вы используете раннюю версию Java и хотите написать файл с указанной кодировкой (encoding), используйте класс OutputStreamWriter для замены.

2- Examples

 package org.o7planning.filewriter.ex; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileWriterEx1 < public static void main(String[] args) throws IOException < // Windows: C:/SomeFolder/out-file.txt File outFile = new File("/Volumes/Data/test/out-file.txt"); outFile.getParentFile().mkdirs(); FileWriter fileWriter = new FileWriter(outFile); System.out.println("Writer file: " + outFile.getAbsolutePath()); System.out.println("With encoding: " + fileWriter.getEncoding()); fileWriter.write("Line 1"); fileWriter.write("\n"); fileWriter.write("Line 2"); fileWriter.write("\n"); fileWriter.write("Line 3"); fileWriter.close(); >> 

FileWriter также позволяет добавлять данные в существующий файл, если файл не существует, он будет создан.

 package org.o7planning.filewriter.ex; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileWriterEx2 < public static void main(String[] args) throws IOException < // Windows: C:/SomeFolder/out-file.txt File outFile = new File("/Volumes/Data/test/out-file.txt"); outFile.getParentFile().mkdirs(); // FileWriter(File outFile, boolean append) FileWriter fileWriter = new FileWriter(outFile, true); System.out.println("Writer file: " + outFile.getAbsolutePath()); System.out.println("With encoding: " + fileWriter.getEncoding()); fileWriter.write("Line 4"); fileWriter.write("\n"); fileWriter.append("Line 5").append("\n"); fileWriter.close(); >> 

Например, используйте FileWriter для записи файла с кодировкой UTF-16, а затем прочитайте файл с помощью FileInputStream для просмотра bytes в файле.

 package org.o7planning.filewriter.ex; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; public class FileWriter_UTF16_Ex1 < // Windows: C:/SomeFolder/out-utf16-file.txt private static final String filePath = "/Volumes/Data/test/out-utf16-file.txt"; public static void main(String[] args) throws IOException < System.out.println("--- Write UTF-16 File ---"); write_UTF16_File(); System.out.println("--- Read File as Binary Stream ---"); readAsInputStream(); >private static void write_UTF16_File() throws IOException < File outFile = new File(filePath); outFile.getParentFile().mkdirs(); // FileWriter(File outFile, boolean append) FileWriter fileWriter = new FileWriter(outFile, StandardCharsets.UTF_16); fileWriter.write("JP日本-八洲"); fileWriter.close(); >private static void readAsInputStream() throws IOException < File file = new File(filePath); FileInputStream fis = new FileInputStream(file); int byteCode; while ((byteCode = fis.read()) != -1) < System.out.println((char) byteCode + " " + byteCode); >fis.close(); > > 
 --- Write UTF-16 File --- --- Read File as Binary Stream --- þ 254 ÿ 255 0 J 74 0 P 80 e 101 å 229 g 103 , 44 0 - 45 Q 81 k 107 m 109 2 50 

Ниже приведена иллюстрация bytes на FileWriter и bytes в файле, только что написанном FileWriter:

Первые два bytes (254, 255) в файле UTF-16 используются для обозначения того, что он запускает данные в кодировке UTF-16.

Ознакомьтесь с моими статьями о InputStreamReader и OutputStreamWriter, чтобы узнать больше о том, как Java читает и записывает кодировки UTF-16 и UTF-8.

View more Tutorials:

Это онлайн курс вне вебсайта o7planning, который мы представляем, он включает бесплатные курсы или курсы со скидкой.

  • AWS Certified Solutions Architect Practice Tests For 2017
  • Design Patterns in C# and .NET
  • Java Object-Oriented Programming : Build a Quiz Application
  • PHP & MySQL For Beginners
  • JavaFX tutorial: Learn JavaFX with Examples
  • Learn Ruby and Rails: Build a blog from scratch step by step
  • * * Code a ‘Coming Soon’ Landing Page in Bootstrap 4
  • Complete Flutter development — build 14 ios and android apps
  • Practice advanced SQL queries with MySQL 5.7+
  • Swift — Advanced API’s & Technique
  • SQL in an Hour with PostgreSQL
  • Oracle SQL Developer : Essentials, Tips and Tricks
  • Master ReactJS: Learn React JS from Scratch
  • Complete Step By Step Java For Testers
  • Learning Path: Android: App Development with Android N
  • Beginning Web Components with Dart
  • Learn To Build An Elearning Website Using NodeJS
  • Master ExpressJS to Build Web Apps with NodeJS&JavaScript
  • Web Scraping with Python, Ruby & import. io
  • iOS программирование на Swift в Xcode — Max level (50 часов)
  • Build Outstanding Java Apps with JavaFX much faster
  • Learn SSRS SQL Reporting & Business Intelligence Essentials
  • Web Programming with Python
  • Master Java Web Services and RESTful API with Spring Boot
  • Learn Hibernate 4 : Java’s Popular ORM Framework

Источник

Читайте также:  Выделить все элементы css
Оцените статью