www.baeldung.com
Open in
urlscan Pro
2606:4700:3108::ac42:2b08
Public Scan
Submitted URL: http://www.baeldung.com/java-write-to-file
Effective URL: https://www.baeldung.com/java-write-to-file
Submission: On January 04 via manual from IT — Scanned from IT
Effective URL: https://www.baeldung.com/java-write-to-file
Submission: On January 04 via manual from IT — Scanned from IT
Form analysis
0 forms found in the DOMText Content
WE VALUE YOUR PRIVACY We and our partners store and/or access information on a device, such as cookies and process personal data, such as unique identifiers and standard information sent by a device for personalised ads and content, ad and content measurement, and audience insights, as well as to develop and improve products. With your permission we and our partners may use precise geolocation data and identification through device scanning. You may click to consent to our and our 760 partners’ processing as described above. Alternatively you may access more detailed information and change your preferences before consenting or to refuse consenting. Please note that some processing of your personal data may not require your consent, but you have a right to object to such processing. Your preferences will apply to this website only. You can change your preferences at any time by returning to this site or visit our privacy policy. MORE OPTIONSAGREE * * * Start Here * Courses ▼▲ * REST WITH SPRING The canonical reference for building a production grade API with Spring * LEARN SPRING SECURITY ▼▲ THE unique Spring Security education if you’re working with Java today * LEARN SPRING SECURITY CORE Focus on the Core of Spring Security 6 * LEARN SPRING SECURITY OAUTH Focus on the new OAuth2 stack in Spring Security 6 * LEARN SPRING From no experience to actually building stuff * LEARN SPRING DATA JPA The full guide to persistence with Spring Data JPA * Guides ▼▲ * PERSISTENCE The Persistence with Spring guides * REST The guides on building REST APIs with Spring * SECURITY The Spring Security guides * About ▼▲ * FULL ARCHIVE The high level overview of all the articles on the site. * BAELDUNG EBOOKS Discover all of our eBooks * ABOUT BAELDUNG About Baeldung. * * JAVA – WRITE TO FILE Last updated: December 1, 2023 Written by: Eugen Paraschiv * Java IO * Java FileWriter Course – LS – All GET STARTED WITH SPRING AND SPRING BOOT, THROUGH THE LEARN SPRING COURSE: >> CHECK OUT THE COURSE 1. OVERVIEW In this tutorial, we’ll explore different ways to write to a file using Java. We’ll make use of BufferedWriter, PrintWriter, FileOutputStream, DataOutputStream, RandomAccessFile, FileChannel, and the Java 7 Files utility class. We’ll also look at locking the file while writing and discuss some final takeaways on writing to file. This tutorial is part of the Java “Back to Basics” series here on Baeldung. FURTHER READING: JAVA – APPEND DATA TO A FILE A quick and practical guide to appending data to files. Read more → FILENOTFOUNDEXCEPTION IN JAVA A quick and practical guide to FileNotFoundException in Java. Read more → HOW TO COPY A FILE WITH JAVA Take a look at some common ways of copying files in Java. Read more → 2. WRITE WITH BUFFEREDWRITER Let’s start simple and use BufferedWriter to write a String to a new file: public void whenWriteStringUsingBufferedWritter_thenCorrect() throws IOException { String str = "Hello"; BufferedWriter writer = new BufferedWriter(new FileWriter(fileName)); writer.write(str); writer.close(); }Copy The output in the file will be: HelloCopy We can then append a String to the existing file: @Test public void whenAppendStringUsingBufferedWritter_thenOldContentShouldExistToo() throws IOException { String str = "World"; BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true)); writer.append(' '); writer.append(str); writer.close(); }Copy The file will then be: Hello WorldCopy 3. WRITE WITH PRINTWRITER Next, let’s see how we can use PrintWriter to write formatted text to a file: @Test public void givenWritingStringToFile_whenUsingPrintWriter_thenCorrect() throws IOException { FileWriter fileWriter = new FileWriter(fileName); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.print("Some String"); printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000); printWriter.close(); }Copy The resulting file will contain: Some String Product name is iPhone and its price is 1000$Copy Note how we’re not only writing a raw String to a file, but also some formatted text with the printf method. We can create the writer using FileWriter, BufferedWriter, or even System.out. 4. 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 into bytes and writes the bytes to a file using FileOutputStream: @Test public void givenWritingStringToFile_whenUsingFileOutputStream_thenCorrect() throws IOException { String str = "Hello"; FileOutputStream outputStream = new FileOutputStream(fileName); byte[] strToBytes = str.getBytes(); outputStream.write(strToBytes); outputStream.close(); }Copy The output in the file will of course be: HelloCopy 5. WRITE WITH DATAOUTPUTSTREAM Next, let’s take a look at how we can use DataOutputStream to write a String to a file: @Test public void givenWritingToFile_whenUsingDataOutputStream_thenCorrect() throws IOException { String value = "Hello"; FileOutputStream fos = new FileOutputStream(fileName); DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos)); outStream.writeUTF(value); outStream.close(); // verify the results String result; FileInputStream fis = new FileInputStream(fileName); DataInputStream reader = new DataInputStream(fis); result = reader.readUTF(); reader.close(); assertEquals(value, result); }Copy 6. WRITE WITH RANDOMACCESSFILE Let’s now illustrate how to write and edit inside an existing file rather than just writing to a completely new file or appending to an existing one. Simply put: We need random access. RandomAccessFile enables us to write at a specific position in the file given the offset — from the beginning of the file — in bytes. This code writes an integer value with offset given from the beginning of the file: private void writeToPosition(String filename, int data, long position) throws IOException { RandomAccessFile writer = new RandomAccessFile(filename, "rw"); writer.seek(position); writer.writeInt(data); writer.close(); }Copy If we want to read the int stored at a specific location, we can use this method: private int readFromPosition(String filename, long position) throws IOException { int result = 0; RandomAccessFile reader = new RandomAccessFile(filename, "r"); reader.seek(position); result = reader.readInt(); reader.close(); return result; }Copy To test our functions, let’s write an integer, edit it, and finally read it back: @Test public void whenWritingToSpecificPositionInFile_thenCorrect() throws IOException { int data1 = 2014; int data2 = 1500; writeToPosition(fileName, data1, 4); assertEquals(data1, readFromPosition(fileName, 4)); writeToPosition(fileName2, data2, 4); assertEquals(data2, readFromPosition(fileName, 4)); }Copy 7. WRITE WITH FILECHANNEL If we are dealing with large files, FileChannel can be faster than standard IO. The following code writes String to a file using FileChannel: @Test public void givenWritingToFile_whenUsingFileChannel_thenCorrect() throws IOException { RandomAccessFile stream = new RandomAccessFile(fileName, "rw"); FileChannel channel = stream.getChannel(); String value = "Hello"; byte[] strBytes = value.getBytes(); ByteBuffer buffer = ByteBuffer.allocate(strBytes.length); buffer.put(strBytes); buffer.flip(); channel.write(buffer); stream.close(); channel.close(); // verify RandomAccessFile reader = new RandomAccessFile(fileName, "r"); assertEquals(value, reader.readLine()); reader.close(); }Copy 8. WRITE WITH FILES CLASS 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, and delete files and directories. It can also be used to read and write to a file: @Test public void givenUsingJava7_whenWritingToFile_thenCorrect() throws IOException { String str = "Hello"; Path path = Paths.get(fileName); byte[] strToBytes = str.getBytes(); Files.write(path, strToBytes); String read = Files.readAllLines(path).get(0); assertEquals(str, read); }Copy 9. WRITE TO A TEMPORARY FILE Now let’s try to write to a temporary file. The following code creates a temporary file and writes a String to it: @Test public void whenWriteToTmpFile_thenCorrect() throws IOException { String toWrite = "Hello"; File tmpFile = File.createTempFile("test", ".tmp"); FileWriter writer = new FileWriter(tmpFile); writer.write(toWrite); writer.close(); BufferedReader reader = new BufferedReader(new FileReader(tmpFile)); assertEquals(toWrite, reader.readLine()); reader.close(); }Copy As we can see, it’s just the creation of the temporary file that is interesting and different. After that point, writing to the file is the same. 10. LOCK FILE BEFORE WRITING Finally, when writing to a file, we sometimes need to make extra sure that no one else is writing to that file at the same time. Basically, we need to be able to lock that file while writing. Let’s make use of FileChannel to try locking the file before writing to it: @Test public void whenTryToLockFile_thenItShouldBeLocked() throws IOException { RandomAccessFile stream = new RandomAccessFile(fileName, "rw"); FileChannel channel = stream.getChannel(); FileLock lock = null; try { lock = channel.tryLock(); } catch (final OverlappingFileLockException e) { stream.close(); channel.close(); } stream.writeChars("test lock"); lock.release(); stream.close(); channel.close(); }Copy Note that if the file is already locked when we try to acquire the lock, an OverlappingFileLockException will be thrown. 11. NOTES After exploring so many methods of writing to a file, let’s discuss some important notes: * If we try to read from a file that doesn’t exist, a FileNotFoundException will be thrown. * If we try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown. * It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it. * In output stream, the close() method calls flush() before releasing the resources, which forces any buffered bytes to be written to the stream. Looking at the common usage practices, we can see, for example, that PrintWriter is used to write formatted text, FileOutputStream to write binary data, DataOutputStream to write primitive data types, RandomAccessFile to write to a specific position, and FileChannel to write faster in larger files. Some of the APIs of these classes do allow more, but this is a good place to start. 12. CONCLUSION This article illustrated the many options of writing data to a file using Java. The implementation of all these examples and code snippets can be found over on GitHub. Course – LS – All GET STARTED WITH SPRING AND SPRING BOOT, THROUGH THE LEARN SPRING COURSE: >> CHECK OUT THE COURSE res – REST with Spring (eBook) (everywhere) Learning to build your API with Spring? Download the E-book Comments are closed on this article! res – REST API (eBook) (everywhere) Building a REST API with Spring? Download the E-book COURSES * All Courses * All Bulk Courses * All Bulk Team Courses * The Courses Platform SERIES * Java “Back to Basics” Tutorial * Jackson JSON Tutorial * Apache HttpClient Tutorial * REST with Spring Tutorial * Spring Persistence Tutorial * Security with Spring * Spring Reactive Tutorials ABOUT * About Baeldung * The Full Archive * Editors * Jobs * Our Partners * Partner with Baeldung * Terms of Service * Privacy Policy * Company Info * Contact