Add data to file java

Append to a file in java using BufferedWriter, PrintWriter, FileWriter

In this tutorial we will learn how to append content to a file in Java. There are two ways to append:

1) Using FileWriter and BufferedWriter : In this approach we will be having the content in one of more Strings and we will be appending those Strings to the file. The file can be appended using FileWriter alone however using BufferedWriter improves the performance as it maintains a buffer.
2) Using PrintWriter : This is one of best way to append content to a file. Whatever you write using PrintWriter object would be appended to the File.

1) Append content to File using FileWriter and BufferedWriter

import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; class AppendFileDemo < public static void main( String[] args ) < try< String content = "This is my content which would be appended " + "at the end of the specified file"; //Specify the file name and path here File file =new File("C://myfile.txt"); /* This logic is to create the file if the * file is not already present */ if(!file.exists())< file.createNewFile(); >//Here true is to append the content to file FileWriter fw = new FileWriter(file,true); //BufferedWriter writer give better performance BufferedWriter bw = new BufferedWriter(fw); bw.write(content); //Closing BufferedWriter Stream bw.close(); System.out.println("Data successfully appended at the end of file"); >catch(IOException ioe) < System.out.println("Exception occurred:"); ioe.printStackTrace(); >> >
Data successfully appended at the end of file

Lets say myfile.txt content was:

This is the already present content of my file

After running the above program the content would be:

This is the already present content of my fileThis is my content which would be appended at the end of the specified file

2) Append content to File using PrintWriter

PrintWriter gives you more flexibility. Using this you can easily format the content which is to be appended to the File .

import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; class AppendFileDemo2 < public static void main( String[] args ) < try< File file =new File("C://myfile.txt"); if(!file.exists())< file.createNewFile(); >FileWriter fw = new FileWriter(file,true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); //This will add a new line to the file content pw.println(""); /* Below three statements would add three * mentioned Strings to the file in new lines. */ pw.println("This is first line"); pw.println("This is the second line"); pw.println("This is third line"); pw.close(); System.out.println("Data successfully appended at the end of file"); >catch(IOException ioe) < System.out.println("Exception occurred:"); ioe.printStackTrace(); >> >
Data successfully appended at the end of file

Lets say myfile.txt content was:

This is the already present content of my file

After running the above program the content would be:

This is the already present content of my file This is first line This is the second line This is third line

References:

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

Thank you so much Sir! I was actually creating a program in which I needed to create a file once and for all and keep adding data later. But somehow it always created a new file whenever I executed it. My problem is finally solved. Thank you very very very much Sir.

Using FileWriter can i write the key value pair(username = “login_data”) data to a (properties) “config.properties” file instead of .txt file. Thanks in advance 🙂

Источник

Java – Append Data to a File

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

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.

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.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Introduction

In this quick tutorial, we’ll see how we use Java to append data to the content of a file – in a few simple ways.

Let’s start with how we can do this using core Java’s FileWriter.

2. Using FileWriter

Here’s a simple test – reading an existing file, appending some text, and then making sure that got appended correctly:

@Test public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException

Note that FileWriter’s constructor accepts a boolean marking if we want to append data to an existing file.

If we set it to false, then the existing content will be replaced.

3. Using FileOutputStream

Next – let’s see how we can do the same operation – using FileOutputStream:

@Test public void whenAppendToFileUsingFileOutputStream_thenCorrect() throws Exception

Similarly, the FileOutputStream constructor accepts a boolean that should be set to true to mark that we want to append data to an existing file.

4. Using java.nio.file

Next – we can also append content to files using functionality in java.nio.file – which was introduced in JDK 7:

@Test public void whenAppendToFileUsingFiles_thenCorrect() throws IOException

5. Using Guava

To start using Guava, we need to add its dependency to our pom.xml:

 com.google.guava guava 31.0.1-jre 

Now, let’s see how we can start using Guava to append content to an existing file:

@Test public void whenAppendToFileUsingFileWriter_thenCorrect() throws IOException

6. Using Apache Commons IO FileUtils

Finally – let’s see how we can append content to an existing file using Apache Commons IO FileUtils.

First, let’s add the Apache Commons IO dependency to our pom.xml:

Now, let’s see a quick example that demonstrates appending content to an existing file using FileUtils:

@Test public void whenAppendToFileUsingFiles_thenCorrect() throws IOException

7. Conclusion

In this article, we’ve seen how we can append content in multiple ways.

The full implementation of this tutorial 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:

Источник

How to append text to a file in Java

In this quick article, I’ll show you how to append text to an existing file using Java legacy I/O API as well as non-blocking new I/O API (NIO).

The simplest and most straightforward way of appending text to an existing file is to use the Files.write() static method. This method is a part of Java’s new I/O API (classes in java.nio.* package) and requires Java 7 or higher. Here is an example that uses Files.write() to append data to a file:

try  // append data to a file Files.write(Paths.get("output.txt"), "Hey, there!".getBytes(), StandardOpenOption.APPEND); > catch (IOException ex)  ex.printStackTrace(); > 

The above code will append Hey, there! to a file called output.txt . If the file doesn’t exist, it will throw a NoSuchFileException exception. It also doesn’t append a new line automatically which is often required when appending to a text file. If you want to create a new file if it doesn’t already exist and also append new line automatically, use another variant of Files.write() as shown below:

try  // data to append ListString> contents = Arrays.asList("Hey, there!", "What's up?"); // append data to a file Files.write(Paths.get("output.txt"), contents, StandardOpenOption.CREATE, StandardOpenOption.APPEND); > catch (IOException ex)  ex.printStackTrace(); > 

If the file has encoding other than the default character encoding of the operating system, you can specify it like below:

Files.write(Paths.get("output.txt"), contents, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); 

Note: Files.write() is good if you want to append to a file once or a few times only. Because it opens and writes the file every time to the disk, which is a slow operation. For frequent append requests, you should rather BufferedWriter (explained below).

The BufferedWriter class is a part of Java legacy I/O API that can also be used to append text to a file. Here is an example that uses the Files.newBufferedWriter() static method to create a new writer (require Java 8+):

try  // create a writer BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), StandardOpenOption.APPEND); // append text to file bw.write("Hey, there!"); bw.newLine(); bw.write("What's up?"); // close the writer bw.close(); > catch (IOException ex)  ex.printStackTrace(); > 

The above code will append text to file. If the file doesn’t already exist, it will throw a NoSuchFileException exception. However, you can change it to create a new file if not available with the following:

BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), StandardOpenOption.CREATE, StandardOpenOption.APPEND); 
BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); 

If you are using Java 7 or below, you can use FileWriter wrapped in a BufferedWriter object to append data to a file as shown below:

try  // create a writer BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt", true)); // append text to file bw.write("Hey, there!"); bw.newLine(); bw.write("What's up?"); // close the writer bw.close(); > catch (IOException ex)  ex.printStackTrace(); > 

The second argument to the FileWriter constructor will tell it to append data to the file, rather than writing a new file. If the file does not already exist, it will be created.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Читайте также:  Сумма всех значений массива python
Оцените статью