Как писать в файл java

Хотя с помощью ранее рассмотренных классов можно записывать текст в файлы, однако они предназначены прежде всего дл работы с бинарными потоками данных, и их возможностей для полноценной работы с текстовыми файлами недостаточно. И для этой цели служат совсем другие классы, которые являются наследниками абстрактных классов Reader и Writer .
Запись файлов. Класс FileWriter
Класс FileWriter является производным от класса Writer. Он используется для записи текстовых файлов.
Чтобы создать объект FileWriter, можно использовать один из следующих конструкторов:
Так, в конструктор передается либо путь к файлу в виде строки, либо объект File, который ссылается на конкретный текстовый файл. Параметр append указывает, должны ли данные дозаписываться в конец файла (если параметр равен true), либо файл должен перезаписываться.
Запишем в файл какой-нибудь текст:
В конструкторе использовался параметр append со значением false — то есть файл будет перезаписываться. Затем с помощью методов, определенных в базовом классе Writer производится запись данных.
Чтение файлов. Класс FileReader
Класс FileReader наследуется от абстрактного класса Reader и предоставляет функциональность для чтения текстовых файлов.
Для создания объекта FileReader мы можем использовать один из его конструкторов:
А используя методы, определенные в базом классе Reader, произвести чтение файла:
Также мы можем считывать в промежуточный буфер из массива символов:
В данном случае считываем последовательно символы из файла в массив из 256 символов, пока не дойдем до конца файла в этом случае метод read возвратит число -1.
Java Write to File — 4 Ways to Write File in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Java provides several ways to write to file. We can use FileWriter, BufferedWriter, java 7 Files and FileOutputStream to write a file in Java.
Java Write to File
Let’s have a brief look at four options we have for java write to file operation.
- FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.
- BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better. You should use BufferedWriter when the number of write operations is more.
- FileOutputStream: FileWriter and BufferedWriter are meant to write text to the file but when you need raw stream data to be written into file, you should use FileOutputStream to write file in java.
- Files: Java 7 introduced Files utility class and we can write a file using its write function. Internally it’s using OutputStream to write byte array into file.
Java Write to File Example
Here is the example showing how we can write a file in java using FileWriter, BufferedWriter, FileOutputStream, and Files in java. WriteFile.java
These are the standard methods to write a file in java and you should choose any one of these based on your project requirements. That’s all for Java write to file example.
You can checkout more Java IO examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Как записать в файл на Java? Примеры с FileWriter, BufferedWriter, Files и FileOutputStream
Java предоставляет множество способов записи данных файл, поэтому сегодня мы рассмотрим на примере наиболее популярные способы.
Как записать в файл. Теория
FileWriter — это самый простой способ записать информацию в файл. Он предоставляет перегруженный метод write() для записи int, байтового массива и String в файл. FileWriter отлично подходит для записи небольших объемов данных.
BufferedWriter — почти аналогичен FileWriter, но использует внутри себя буфер для записи данных в файл. Если вам нужно записать в файл большие объемы информации, то ваш выбор должен пасть на BufferedWriter.
FileWriter и BufferedWriter хорошо справляются с записью текстовой информации в файл, но когда стоит задача записывать в файл данные потока, то желательно использовать FileOutputStream .
Files — вспомогательный класс для работы с файлами. Он содержит метод, который внутри себя использует OutputStream для записи массива байтов в файл.
Пишем в файл на Java. Практика
Ниже приведена программа для записи информации в файл с помощью классов FileWriter, BufferedWriter, FileOutputStream и Files .
How do I create a file and write to it?
Java 7+ users can use the Files class to write to files:
Creating a text file:
Creating a binary file:
![]()
In Java 7 and up:
There are useful utilities for that though:
-
from commons-io from guava
Note also that you can use a FileWriter , but it uses the default encoding, which is often a bad idea — it’s best to specify the encoding explicitly.
Below is the original, prior-to-Java 7 answer
![]()
![]()
If you already have the content you want to write to the file (and not generated on the fly), the java.nio.file.Files addition in Java 7 as part of native I/O provides the simplest and most efficient way to achieve your goals.
Basically creating and writing to a file is one line only, moreover one simple method call!
The following example creates and writes to 6 different files to showcase how it can be used:
![]()
![]()
A very simple way to create and write to a file in Java:
![]()
![]()
Here’s a little example program to create or overwrite a file. It’s the long version so it can be understood more easily.
Using try() will close stream automatically. This version is short, fast (buffered) and enables choosing encoding.
This feature was introduced in Java 7.
![]()
![]()
Here we are entering a string into a text file:
We can easily create a new file and add content into it.
![]()
There are many ways of writing to a file. Each has its benefits, and each might be simplest in a given scenario.
This answer is centred on Java 8, and tries to cover all the details needed for the Java Professional Exam. Classes involved include:
There are 5 main ways of writing to a file:
Each has its own distinctive benefits:
- OutputStreamWriter — The most basic way before Java 5
- FileWriter – Optional append constructor argument
- PrintWriter – Lots of methods
- Files.write() – Create and write to a file in a single call
- Files.newBufferedWriter() – Makes it easy to write large files
Below are details of each.
FileOutputStream
This class is meant for writing streams of raw bytes. All the Writer approaches below rely on this class, either explicitly or under the hood.
Note that the try-with-resources statement takes care of stream.close() and that closing the stream flushes it, like stream.flush() .
OutputStreamWriter
This class is a bridge from character streams to byte streams. It can wrap a FileOutputStream , and write strings:
BufferedWriter
This class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
It can wrap an OutputStreamWriter :
Pre Java 5 this was the best approach for large files (with a regular try/catch block).
FileWriter
This is a subclass of the OutputStreamWriter , and is a convenience class for writing character files:
The key benefit is that it has an optional append constructor argument, which determines whether it appends to or overwrites the existing file. Note that the append/overwrite behaviour is not controlled by the write() and append() methods, which behave in nearly the same way.
- There is no buffering, but to handle large files it can be wrapped in a BufferedWriter .
- FileWriter uses the default encoding. It’s often preferable to specify encoding explicitly
PrintWriter
This class prints formatted representations of objects to a text-output stream. Under the hood it is the same as the BufferedWriter approach above ( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(. ))) ). PrintWriter was introduced in Java 5 as a convenient way to call this idiom, and adds additional methods such as printf() and println() .
Methods in this class don’t throw I/O exceptions. You can check errors by calling checkError() . The destination of a PrintWriter instance can be a File, OutputStream or Writer. Here is an example of writing to a file:
When writing to an OutputStream or Writer there is an optional autoFlush constructor parameter, which is false by default. Unlike the FileWriter , it will overwrite any existing file.
Files.write()
Java 7 introduced java.nio.file.Files . Files.write() lets you create and write to a file in a single call.
@icza’s answer shows how to use this method. A couple of examples:
This does not involve a buffer, so it’s not suitable for large files.
Files.newBufferedWriter()
Java 7 also introduced Files.newBufferedWriter() which makes it easy to get a BufferedWriter :
This is similar to PrintWriter , with the downside of not having PrintWriter’s methods, and the benefit that it doesn’t swallow exceptions.
Since the author did not specify whether they require a solution for Java versions that have been EoL’d (by both Sun and IBM, and these are technically the most widespread JVMs), and due to the fact that most people seem to have answered the author’s question before it was specified that it is a text (non-binary) file, I have decided to provide my answer.
First of all, Java 6 has generally reached end of life, and since the author did not specify he needs legacy compatibility, I guess it automatically means Java 7 or above (Java 7 is not yet EoL’d by IBM). So, we can look right at the file I/O tutorial: https://docs.oracle.com/javase/tutorial/essential/io/legacy.html
- Many methods didn’t throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a «delete fail» but wouldn’t know if it was because the file didn’t exist, the user didn’t have permissions, or there was some other problem.
- The rename method didn’t work consistently across platforms.
- There was no real support for symbolic links.
- More support for metadata was desired, such as file permissions, file owner, and other security attributes. Accessing file metadata was inefficient.
- Many of the File methods didn’t scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service.
- It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.
Oh well, that rules out java.io.File. If a file cannot be written/appended, you may not be able to even know why.
Here’s an example (simplified):
Another example (append):
Simplified example (Java 8 or up):
Another example (append):
These methods require minimal effort on the author’s part and should be preferred to all others when writing to [text] files.
![]()
![]()
If you wish to have a relatively pain-free experience you can also have a look at the Apache Commons IO package, more specifically the FileUtils class.
Never forget to check third-party libraries. Joda-Time for date manipulation, Apache Commons Lang StringUtils for common string operations and such can make your code more readable.
Java is a great language, but the standard library is sometimes a bit low-level. Powerful, but low-level nonetheless.
Here are some of the possible ways to create and write a file in Java :
Using FileOutputStream
Using FileWriter
Using PrintWriter
Using OutputStreamWriter
For further check this tutorial about How to read and write files in Java .
If you for some reason want to separate the act of creating and writing, the Java equivalent of touch is
createNewFile() does an existence check and file create atomically. This can be useful if you want to ensure you were the creator of the file before writing to it, for example.
![]()
![]()
best way is to use Java7: Java 7 introduces a new way of working with the filesystem, along with a new utility class – Files. Using the Files class, we can create, move, copy, delete files and directories as well; it also can be used to read and write to a file.
Write with FileChannel If you are dealing with large files, FileChannel can be faster than standard IO. The following code write String to a file using FileChannel:
Write with DataOutputStream
Write with FileOutputStream
Let’s now see how we can use FileOutputStream to write binary data to a file. The following code converts a String int bytes and writes the bytes to file using a FileOutputStream:
Write with PrintWriter we can use a PrintWriter to write formatted text to a file:
Write with BufferedWriter: use BufferedWriter to write a String to a new file:
append a String to the existing file:
![]()
I think this is the shortest way:
![]()
To create file without overwriting existing file:
![]()
It’s worth a try for Java 7+:
It looks promising.
![]()
![]()
In Java 8 use Files and Paths and using try-with-resources construct.
![]()
![]()
![]()
![]()
The simplest way I can find:
It will probably only work for 1.7+.
![]()
![]()
One line only ! path and line are Strings
![]()
![]()
File reading and writing using input and outputstream:
![]()
![]()
Just include this package:
And then you can use this code to write the file:
![]()
If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.
There are few points to note:
- It is always a good habit to specify charset encoding and for that we have constant in class StandardCharsets .
- The code uses try-with-resource statement in which resources are automatically closed after the try.
Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential we can make use of stream APIs in Java:
![]()
Using Google’s Guava library, we can create and write to a file very easily.
The example creates a new fruits.txt file in the project root directory.
There are some simple ways, like:
![]()
You can even create a temporary file using a system property, which will be independent of which OS you are using.
![]()
There are at least several ways of creating a file and writing to it:
Small files (1.7)
You can use one of the write methods to write bytes, or lines, to a file.
These methods take care of most of the work for you, such as opening and closing the stream, but are not intended for handling large files.
Writing larger File by Using Buffered Stream I/O (1.7)
The java.nio.file package supports channel I/O, which moves data in buffers, bypassing some of the layers that can bottleneck stream I/O.
This approach is preferential due to its efficient performance especially when completing a large amount of write operations. Buffered operations have this effect as they aren’t required to call the operating system’s write method for every single byte, reducing on costly I/O operations.
Using NIO API to copy (and create a new one) a file with an Outputstream (1.7)
There are also additional methods that allow to copy all bytes from an input stream to a file.
FileWriter (text) (<1.7)
Writes directly into file (less performance) and should be used only when number of writes are less. Used to write character-oriented data to a file.
FileOutputStream (binary) (<1.7)
FileOutputStream is meant for writing streams of raw bytes such as image data.
With this approach one should consider to always write an array of bytes rather than writing one byte at a time. The speedup can be quite significant — up to 10 x higher or more. Therefore it is recommended to use the write(byte[]) methods whenever possible.