In Java, you can write text to a file using the following classes.
- BufferedWriter
- PrintWriter
- FileOutputStream
- Files
Let`s see with an example.
Write a file using BufferedWriter
The following is an example of writing text to the text.txt
file using BufferedWriter.
File file = new File("/home/js/test/text.txt");
String str = "Hello world!";
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(str);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
If the file doesn`t exist, it creates a file, enters text and saves it.
Importantly, if you use a BufferedWriter, you must close the FileDescriptor by calling close()
at the end.
If we use Try-with-resources like the code below, we dont need to call it because try calls
close()` at the end.
File file = new File("/home/js/test/text.txt");
String str = "Hello world!";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(str);
} catch (IOException e) {
e.printStackTrace();
}
You can use append()
instead of append()
to enter text multiple times.
File file = new File("/home/js/test/text.txt");
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.append("Hello~\n");
writer.append("World!");
} catch (IOException e) {
e.printStackTrace();
}
Write a file using PrintWriter
The following is an example of writing text to a file with PrintWriter.
File file = new File("/home/js/test/text.txt");
try {
FileWriter fileWriter = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Hello~\n");
printWriter.print("World!");
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
You can input multiple texts with print()
. You must also call close()
at the end of this.
If we implement it using Try-with-resources like this, we dont have to call
close()`.
File file = new File("/home/js/test/text.txt");
try (FileWriter fileWriter = new FileWriter(file)) {
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Hello~\n");
printWriter.print("World!");
} catch (IOException e) {
e.printStackTrace();
}
Write a file using FileOutputStream
The following is an example of writing text to a file using FileOutputStream. You need to convert String to byte and write to Stream.
File file = new File("/home/js/test/text.txt");
String str = "Hello World";
byte[] bytes = str.getBytes();
try {
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(bytes);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
You can also implement it using Try-with-resources like this:
File file = new File("/home/js/test/text.txt");
String str = "Hello World";
byte[] bytes = str.getBytes();
try (FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
Write a file using Files
The following code is an example of writing a string to a file using Files.
String str = "Hello";
byte[] bytes = str.getBytes();
Path path = Paths.get("/home/js/test/text.txt");
try {
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
Convert String to byte and pass it as an argument to write()
.
Inside Files.write()
write string to file as OutputStream.
It also calls close()
so we dont have to call
close()`.
For reference, the code below is the actual implementation code of Java Files.write()
.
public static Path write(Path path, byte[] bytes, OpenOption... options)
throws IOException
{
// ensure bytes is not null before opening file
Objects.requireNonNull(bytes);
try (OutputStream out = Files.newOutputStream(path, options)) {
int len = bytes.length;
int rem = len;
while (rem > 0) {
int n = Math.min(rem, BUFFER_SIZE);
out.write(bytes, (len-rem), n);
rem -= n;
}
}
return path;
}
Reference
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)