Write content to file in java

Java – Write to File

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

Читайте также:  Obfuscation in java code

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, 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

FileNotFoundException in Java

How to Copy a File with Java

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

The output in the file will be:

We can then append a String to the existing file:

@Test public void whenAppendStringUsingBufferedWritter_thenOldContentShouldExistToo() throws IOException

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

The resulting file will contain:

Some String Product name is iPhone and its price is 1000$

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

The output in the file will of course be:

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

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

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

To test our functions, let’s write an integer, edit it, and finally read it back:

@Test public void whenWritingToSpecificPositionInFile_thenCorrect() throws IOException

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

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

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

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.

Читайте также:  Generate hash from string python

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

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.

Читайте также:  Php посмотреть все post

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.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Java Write To File Examples

Last updated: 02 February 2020 In this post we will look at five different examples on how to write to a file using Java. The code sinppets check to see if the file exists before writing to the file, otherwise a file is created.

Write to file using BufferedWriter

import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class WriteToFile < public static void main( String[] args ) < try < String content = "Content to write to file"; //Name and path of the file File file = new File("writefile.txt"); if(!file.exists())< file.createNewFile(); >FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); > catch(IOException ex) < System.out.println("Exception occurred:"); ex.printStackTrace(); >> > 

Note: If we want to append to a file, we need to initialize the FileWriter with the true parameter:

FileWriter fw = new FileWriter(file, true); 

Write to file using PrintWriter

import java.io.*; public class WriteToFile < public static void main( String[] args ) < try < String content = "Content to write to file"; //Name and path of the file File file = new File("writefile.txt"); if(!file.exists())< file.createNewFile(); >FileWriter fw = new FileWriter(file); PrintWriter bw = new PrintWriter(fw); bw.write(content); bw.close(); > catch(IOException ex) < System.out.println("Exception occurred:"); ex.printStackTrace(); >> > 

Write to file using FileOutputStream

import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class WriteToFile < public static void main( String[] args ) < try < String content = "Content to write to file"; //Name and path of the file File file = new File("writefile.txt"); if(!file.exists())< file.createNewFile(); >FileOutputStream outStream = new FileOutputStream(file); byte[] strToBytes = content.getBytes(); outStream.write(strToBytes); outStream.close(); > catch(IOException ex) < System.out.println("Exception occurred:"); ex.printStackTrace(); >> > 

Write to file using Files class

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class WriteToFile < public static void main( String[] args ) < Path path = Paths.get("writefile.txt"); String content = "Content to write to file"; try < byte[] bytes = content.getBytes(); Files.write(path, bytes); >catch(IOException ex) < System.out.println("Exception occurred:"); ex.printStackTrace(); >> > 

Write to file using DataOutputStream

import java.io.*; public class WriteToFile < public static void main( String[] args ) < String content = "Content to write to file"; try < File file = new File("writefile.txt"); if(!file.exists())< file.createNewFile(); >FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dataOutStream = new DataOutputStream(bos); dataOutStream.writeUTF(content); dataOutStream.close(); > catch(IOException ex) < System.out.println("Exception occurred:"); ex.printStackTrace(); >> > 

Источник

Оцените статью