Write list in file java

Java — Как я могу записать свой ArrayList в файл и прочитать (загрузить) этот файл в исходный ArrayList?

Я пишу программу на Java, которая отображает ряд афтершоульных клубов (E.G. Football, Hockey — введенный пользователем). Клубы добавляются в следующий ArrayList :

private ArrayList clubs = new ArrayList(); 
public void addClub(String clubName)
public class Club < private String name; public Club(String name) < this.name = name; >//There are more methods in my program but don't affect my query.. > 

Моя программа работает — она ​​позволяет мне добавить новый клубный объект в мой arraylist, я могу просмотреть arraylist, и я могу удалить все, что хочу, и т.д. Тем не менее, теперь я хочу сохранить этот массивList (клубы) в файл, а затем я хочу, чтобы иметь возможность загружать файл позже, и тот же arraylist там снова. У меня есть два метода для этого (см. ниже) и пытались заставить его работать, но havent hashluck, любая помощь или совет будут оценены. Сохранить метод (имя_файла выбрано пользователем)

public void save(String fileName) throws FileNotFoundException
public void load(String fileName) throws FileNotFoundException

Я также использую GUI для запуска приложения, и на данный момент я могу нажать кнопку «Сохранить», чтобы затем ввести имя и местоположение и сохранить его. Файл появляется и может быть открыт в «Блокноте», но отображается как что-то вроде Club @c5d8jdj (для каждого Клуба в моем списке)

Читайте также:  Copy to clipboard with javascript

То, что вы видите [email protected] является результатом метода toString() класса Object. Как бы вы хотели, чтобы список был сохранен в файле? Какой формат?

Если вы хотите сделать это таким образом, вы должны переопределить метод toString () класса Club (), чтобы он содержал всю информацию, а затем конструктор, который может воссоздать объект. Или взгляните на Serializable интерфейс и ObjectStreams: docs.oracle.com/javase/tutorial/essential/io/objectstreams.html

У меня нет никаких предпочтений, в каком формате он сохраняется, если его можно загрузить позже в приложении.

Источник

Write and read an ArrayList object to a file in Java

Today, we will get to know how to write an ArrayList object to a file and then load the object back to the Java program form that file. This would help us to store the data to test other features that we added to the program without re-putting the common data.

First, we’ll take a look at the code below

1. Since we will need to use a lot of classes inside java.io, we import everything inside that specific library.

2. Create a class Person with 3 attributes, a constructor function and overriding toString method to print the detail of an object we will initialize later. As this the objects of this class will be used to write to file and then load back, we need to implement the Serializable interface to indicate Java that this class can be serialized or deserialized.

3. inside this main methods we will create 3 objects of the class Person. Then, we create an ArrayList name people and add those 3 Person objects.

Now, we are ready to write this Arraylist into a file.

Write an object into a file.

We add this code to the main method.

//write to file try< FileOutputStream writeData = new FileOutputStream("peopledata.ser"); ObjectOutputStream writeStream = new ObjectOutputStream(writeData); writeStream.writeObject(people); writeStream.flush(); writeStream.close(); >catch (IOException e)

Because writing and reading data can cause Error we need to use a try catch block to handle the Exception that can occur.

FileOutputStream writeData = new FileOutputStream(“peopledata.ser”): Creates a file output stream to write to the file that we provide inside the parentheses. You can provide the path to the file if you want, in this case, I just give the file name, so that the file will be stored in the same folder with the .java file

ObjectOutputStream writeStream = new ObjectOutputStream(writeData): ObjectOutputStream will handle the object to be written into the file that FileOutputStream created.

FileOutputStream and ObjectOutputStream should come together in order to write an object to a file.

writeStream.writeObject(people): tell the program to write this peple object which is an ArrayList that we’ve just created above into the file peopledata.ser
writeStream.flush(): using the flush method here is not really necessary but it’s a good practice to have flush() since it will flush all the data in the stream, make sure data is written into the file.
writeStream.close(); we close the stream after the writing is done. This also releases the system resources.

Open the file peopledata.ser and you will see that there is something written. Don’t be afraid that you can’t read it, Java can.

��srjava.util.ArrayListx����a�IsizexpwsrPerson-ĩ��9/I birthYearL firtNametLjava/lang/String;L lastNameq~xp�tJonytDeepsq ~�tAndrewtJustinsq~�tValaktSusanx

Reading the data from a file

Writing is done, now we can load the data from the file to be used in our program.

Append the code below to the main method

try < FileInputStream readData = new FileInputStream("peopledata.ser"); ObjectInputStream readStream = new ObjectInputStream(readData); ArrayListpeople2 = (ArrayList) readStream.readObject(); readStream.close(); System.out.println(people2.toString()); >catch (Exception e)

Still, we use try-catch to ensure that all the exceptions will be caught.

FileInputStream readData = new FileInputStream(“peopledata.ser”) & ObjectInputStream readStream = new ObjectInputStream(readData): note that this time we use Input instead of Ouput since we want to read from the file into the program.

ArrayList people2 = (ArrayList) readStream.readObject(): We create a new ArrayList people2 just to make sure this is a new object that is distinct from the existing people object. We assign the value that we reed form the file “peopledata.ser” and make sure we cast the value into an ArrayList of Person.

readStream.close(): close the reading stream.

System.out.println(people2.toString()): print the new ArrayList to the console to see if all the data is loaded correctly.

import java.io.*; import java.util.ArrayList; public class Person implements Serializable < private String firstName; private String lastName; private int birthYear; public Person(String firtName, String lastName, int birthYear) < this.firstName = firtName; this.lastName = lastName; this.birthYear = birthYear; >@Override public String toString() < return "Person\n"; > public static void main(String[] args) < Person p1 = new Person("Jony", "Deep", 1980); Person p2 = new Person("Andrew", "Justin", 1990); Person p3 = new Person("Valak", "Susan", 1995); ArrayListpeople = new ArrayList<>(); people.add(p1); people.add(p2); people.add(p3); //write to file try< FileOutputStream writeData = new FileOutputStream("peopledata.ser"); ObjectOutputStream writeStream = new ObjectOutputStream(writeData); writeStream.writeObject(people); writeStream.flush(); writeStream.close(); >catch (IOException e) < e.printStackTrace(); >try< FileInputStream readData = new FileInputStream("peopledata.ser"); ObjectInputStream readStream = new ObjectInputStream(readData); ArrayList people2 = (ArrayList) readStream.readObject(); readStream.close(); System.out.println(people2.toString()); >catch (IOException | ClassNotFoundException e) < e.printStackTrace(); >> >

Источник

Как записать 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 и его методами можно в документации

Источник

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:

Источник

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.

Источник

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