I have a problem with ArrayList - there is a Library class, it has a list of books that are in a text file and need to be driven into ArrayList. It is necessary that ArrayList read data from a file in the format Name, Year, Author.

For entering into the file, I registered a method that basically writes text information from the console to a text file. But everything would be fine if I just had to write text into a .txt file. But there is nothing simple in our business, and I need to specify the formatted data entry into a text file. Here is the method I use to write.

if (sc==6){ System.out.println("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ Π½ΠΎΠ²ΡƒΡŽ ΠΊΠ½ΠΈΠ³Ρƒ:"); String filePath = "Lib.txt"; Scanner console = new Scanner(System.in); try {FileWriter out = new FileWriter(filePath, true); BufferedWriter bufferWriter = new BufferedWriter(out); bufferWriter.newLine(); bufferWriter.write(console.next()); bufferWriter.close(); } catch (IOException e) { System.err.println(e); } } 

Here is an example of the method I use to read.

 public static void main(String[] args) throws IOException { Bks books = new Bks (); String line = null; ArrayList<Bk> list = new ArrayList<>(); try { BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream("Lib.txt"), "Cp1251")); while ((line = reader.readLine()) != null) { String[] items = line.split(","); list.add(new Bk(items[0], items[1], Integer.parseInt(items[2]))); } reader.close(); } catch (Exception ex) { ex.printStackTrace(); } books.setArr(list); 

Advise what I need to add here, and what to change?

  • And what specifically does not work? - iksuy
  • one
    There are a lot of problems in principle. You need to set the formatted input through the console, so that the program would request, first the Name, then the Year, and then the Author. Then you need to write all this into a text file, and then read it all back to the console. I understand that the write method must write data to the ArrayList cells. Which are in the line-- list.add (new Bk (items [0], items [1], Integer.parseInt (items [2]))); But how to do it, I do not know. - OrlyI

1 answer 1

First, try, please, construct with reader.ready ():

 while(reader.ready()){ String readLine = reader.readLine(); if(readLine != null){ // ΠΎΠΏΠ΅Ρ€Π°Ρ†ΠΈΠΈ со строкой } } 

For a formatted writing of strings to a file, you can use String.format () with parameters:

  String stringValue = "Π― строка!"; int integerValue = 42; String s = String.format("%1$s,%2$d", stringValue,integerValue); // s == "Π― строка!,42" 

And then general recommendations (if this program is considered as a working draft, and not a training exercise):

  1. It is better to work with unicode (utf-8 encoding instead of cp1251). This will make it possible to use the application in systems around the world.

  2. SQLite or MongoDB may be suitable as data storage for such an application. From experience, I will say that MongoDB is very simple and convenient when it comes to storing small text records, plus less hassle with formatting data - just write the values ​​for the fields (name, author, etc.), and mongo will save the records as needed. Plus, a convenient presentation of data in JSON format, if you need to transfer something over the network (for example, the mobile version of the application).

UPD: For the program to request the name, year and the author, organize a dialogue with the user:

 Scanner console = new Scanner(System.in); System.out.print("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ Π½Π°Π·Π²Π°Π½ΠΈΠ΅ ΠΊΠ½ΠΈΠ³ΠΈ: "); if(console.hasNextLine()){ name = console.nextLine(); } System.out.print("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ Π΄Π°Ρ‚Ρƒ: "); if(console.hasNextLine()){ date = console.nextLine(); } System.out.print("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ Автора: "); if(console.hasNextLine()){ author = console.nextLine(); } // \t - символ табуляции String line = String.format("%1$s\t%2$s\t%3$s", name,date,author); System.out.println(line); 

Further, the resulting string (instead of tabulation, you can use any character: a comma, like yours or a semicolon ";", as in CSV format) can be safely written to a file.

To output data from a file, start the cycle of reading data from a file, fill in rows (nextLine) with an ArrayList instance (you can split each line with a separator and rebuild with the necessary format: first split([Ρ€Π°Π·Π΄Π΅Π»ΠΈΡ‚Π΅Π»ΡŒ]) , then String.format([шаблон строки],[Π΄Π°Π½Π½Ρ‹Π΅]) ), and then - display in portions, for example, 10 items each.

 List<String> library = new ArrayList<>(); // для ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π°, заполняю лист ΠΏΠΎΡ‡Ρ‚ΠΈ ΠΎΠ΄ΠΈΠ½Π°ΠΊΠΎΠ²Ρ‹ΠΌΠΈ строками for(int i = 0; i < 100 ; i++){ library.add(line + Math.random()); } for(int counter = 0; counter < library.size(); counter++){ System.out.println(library.get(counter)); if(counter % 10 == 0){ console.nextLine(); } }