Java collection save to file

How to write an ArrayList values to a file in Java

You can write an ArrayList object values to a plain text file in Java by using the built-in java.nio.file package.

First, create your ArrayList object and add some values to the list as shown below:

Next, use the Paths class to get() the file path using a String as follows:
The Path object represents a path to the file in your system.

After that, you need to call the write() method from the Files class to write the arrList variable values to the output path.

You need to surround the write() method in a try. catch block to handle any exception that might occur when writing the values to the file:

 Once finished, you should see the output.txt generated by JVM in the current working directory of your Java project.

To find the location of the file, you can call the toFile().getAbsolutePath() method from the Path object.

Add a println() method call just below the Files.write() line as shown below:


The text file content should be as follows:

When you want the file to be generated in a different location, you can provide an absolute path as a parameter to the Paths.get() method.

For example, I’d like the file to be generated on my Desktop directory, so I specified the absolute path to the directory below:


Now you’ve learned how to write an ArrayList values to a file using Java. Good work! 👍

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Writing a List of Strings Into a Text File

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.

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

1. Overview

In this quick tutorial, we'll write a List of Strings into a text file in Java in different ways. First, we'll discuss FileWriter, then BufferedWriter, and finally, Files.writeString.

2. Using FileWriter

The java.io package contains a FileWriter class that we can use to write character data to a file. If we look at the hierarchy, we'll see that the FileWriter class extends the OutputStreamWriter class, which in turn extends the Writer class.

Let's have a look at the constructors available to initialize a FileWriter:

FileWriter f = new FileWriter(File file); FileWriter f = new FileWriter(File file, boolean append); FileWriter f = new FileWriter(FileDescriptor fd); FileWriter f = new FileWriter(File file, Charset charset); FileWriter f = new FileWriter(File file, Charset charset, boolean append); FileWriter f = new FileWriter(String fileName); FileWriter f = new FileWriter(String fileName, Boolean append); FileWriter f = new FileWriter(String fileName, Charset charset); FileWriter f = new FileWriter(String fileName, Charset charset, boolean append); 

Note that all the constructors of the FileWriter class assume that the default byte-buffer size and the default character encoding are acceptable.

Now, let's learn how to write a List of Strings into a text file using FileWriter:

FileWriter fileWriter = new FileWriter(TEXT_FILENAME); for (String str : stringList) < fileWriter.write(str + System.lineSeparator()); >fileWriter.close(); return TEXT_FILENAME;

One important thing to note in the example is that the FileWriter creates the sampleTextFile.txt if it isn't present already. If the file exists, then we can overwrite it or append it depending on the choice of the constructor.

3. Using BufferedWriter

The java.io package contains a BufferedWriter class that can be used with other Writers to write character data with better performance. But how is it more efficient?

When we use BufferedWriter, the characters are written to the buffer instead of the disk. When the buffer gets filled, all the data is written to the disk in one go, resulting in reduced traffic from/to the disk, and hence, contributing to better performance.

If we talk about the hierarchy, the BufferedWriter class extends the Writer class.

Let's have a look at the constructors available to initialize a BufferedWriter:

BufferedWriter b = new BufferedWriter(Writer w); BufferedWriter b = new BufferedWriter(Writer w, int size);

Note that it takes the default value if we don't specify the buffer size.

Now, let's explore how to write a List of Strings into a text file using BufferedWriter:

BufferedWriter br = new BufferedWriter(new FileWriter(TEXT_FILENAME)); for (String str : stringList) < br.write(str + System.lineSeparator()); >br.close(); return TEXT_FILENAME;

In the above code, we've wrapped FileWriter with BufferedWriter, which results in reducing read calls and, in turn, improving performance.

3. Using Files.writeString

The java.nio package contains a method writeString() from the Files class to write characters into a file. This method was introduced in Java 11.

Let's have a look at the two overloaded methods available in java.nio.file.Files:

public static Path writeString​(Path path, CharSequence csq, OpenOption… options) throws IOException public static Path writeString​(Path path, CharSequence csq, Charset cs, OpenOption… options) throws IOException

Note that in the first method, we don't have to specify the Charset. By default, it takes UTF-8 Charset, whereas in the second method, we can specify the Charset. Finally, let's learn how to write a List of Strings into a text file using Files.writeString:

Path filePath = Paths.get(TEXT_FILENAME); Files.deleteIfExists(filePath); Files.createFile(filePath); for (String str : stringList) < Files.writeString(filePath, str + System.lineSeparator(), StandardOpenOption.APPEND); >return filePath.toString();

In the example above, we deleted the file if it already existed and then created a file using Files.createFile method. Note that we have set OpenOption field to StandardOperation.APPEND, which means the file will open in append mode. If we don't specify OpenOption, then we can expect two things to happen:

  • The file will be overwritten if it's already present
  • File.writeString will create a new file and write on it if the file doesn't exist

4. Testing

For JUnit tests, let's define a List of Strings:

private static final List stringList = Arrays.asList("Hello", "World"); 

Here, we'll find out the count of lines of the output file using the NIO Files.lines and count(). The count should be equal to the number of Strings in the List.

Now, let's head to testing of our FileWriter implementation:

@Test public void givenUsingFileWriter_whenStringList_thenGetTextFile() throws IOException

Next, we'll test the BufferedWriter implementation:

@Test public void givenUsingBufferedWriter_whenStringList_thenGetTextFile() throws IOException

Finally, let's test our Files.writeString implementation:

@Test public void givenUsingFileWriteString_whenStringList_thenGetTextFile() throws IOException

5. Conclusion

In this article, we explored three common ways of writing a List of Strings into a text file. Also, we tested our implementation by writing JUnit tests.

As always, the complete code for the tutorial is available 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:

Источник

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

Чтобы записать текст в файл прежде всего нужно учесть, что формат итогового файла должен быть удобен для его дальнейшей обработки и не зависеть от языков программирования. Поэтому, в таких случаях рекомендуется использовать формат .json .

Для записи ArrayList в файл необходимо использовать ObjectMapper , он является объектом класса com.fasterxml.jackson.databind.ObjectMapper . В данном случае обязательным условием работы с объектом ObjectMapper является обработка исключения java.io.IOException , поэтому код выполняется в блоке try. catch :

ListString> hello = new ArrayList<>(); hello.add("Hello!"); hello.add("Hello, world!"); hello.add("Hello, Hexlet!"); try  ObjectMapper mapper = new ObjectMapper(); // название файла String fileName = "Hello.json"; // метод для записи данных в файл mapper.writeValue(new File(fileName), hello); > catch (IOException e)  System.out.println("Возникла ошибка во время записи, проверьте данные."); > 

Содержимое файла будет выглядеть следующим образом:

Подробнее ознакомиться с описанием класса java.io.Writer и его методами можно в документации

Источник

Write ArrayList to file java

Write arraylist to file Java

In this article, we will learn various ways to write an ArrayList to file using Java.

2.1. Using FileWriter

You can loop through each element in the array and write it to a file using the FileWriter.

import java.io.FileWriter; import java.util.ArrayList; import java.io.IOException; public class MyClass < public static void main(String args[]) < ArrayListstringArray = new ArrayList(); FileWriter writer = null; try < writer = new FileWriter("file.txt"); for(String str: stringArray) < writer.write(str + System.lineSeparator()); >writer.close(); > catch (IOException e) < System.out.println(e.getMessage()); >> >

2.2. Using java.nio.file.Files

To make it more simple, you can use Files standard java class provided in Java 1.7.

import java.nio.file.Files; import java.util.ArrayList; import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; import java.nio.charset.Charset; public class MyClass < public static void main(String args[]) < ArrayListstringArray = new ArrayList(); Path out = Paths.get("output.txt"); try < Files.write(out,stringArray,Charset.defaultCharset()); >catch (IOException e) < System.out.println(e.getMessage()); >> >

2.3. FileUtils from Apache Commons IO library

FileUtils.writeLines(new File("output.txt"), encoding, list);

You can use below code to write the array of string in one line to a file.

FileUtils.writeStringToFile(new File(theFile), StringUtils.join(theArray, delimiter));

3. Write Arraylist of object to file Java

You can use FileOutputStream and ObjectOutputStream to write the array of objects to a file in Java.

4. Conclusion

To sum up, we have seen different ways to write an array to a file in Java.

Источник

Читайте также:  Html код центровки изображения
Оцените статью