Testing was successful.
package com.codegym.task.task18.task1827;
/*
Prices
C:\Users\Администратор\CodeGymTasks\2.JavaCore\src\com\codegym\task\task18\file27.txt
*/
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
public class Solution {
public static void main(String[] args) throws Exception {
if (args.length == 0 || !args[0].equals("-c")) return;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
reader.close();
FileInputStream fis = new FileInputStream(fileName);
reader = new BufferedReader(new InputStreamReader(fis));
String line;
int maxId = 0, currentId;
while ((line = reader.readLine()) != null) {
currentId = Integer.parseInt(line.substring(0, 8).trim());
if (currentId > maxId) maxId = currentId;
}
fis.close();
reader.close();
String id = String.valueOf(++maxId);
if (args[0].equals("-c")) {
if (args[1].length() > 30)
args[1] = args[1].substring(0, 30);
String newProduct = String.format("%-8s%-30s%-8s%-4s", id, args[1], args[2], args[3]);
FileOutputStream fos = new FileOutputStream(fileName, true);
fos.write(newProduct.getBytes());
fos.close();
}
}
}
/*
Prices
CrUD for a table inside a file.
Read a file name for CrUD operations from the console.
The program is started with the following arguments:
-c productName price quantity
Argument values:
where id is 8 characters.
productName is 30 characters.
price is 8 characters.
quantity is 4 characters.
-c adds the product with the specified parameters to the end of the file, and generates an id by
incrementing the maximum id found in the file. - *добавляет продукт с указанными параметрами в конец
файла и генерирует идентификатор, увеличивая максимальный идентификатор, найденный в файле.
The file data is stored in the following order (without separating spaces):
id productName price quantity
Each data field is padded with spaces up to its length.
*Каждое поле данных заполняется пробелами до его длины.
Before adding a new line, re-write all of its contents to the file.
*Перед добавлением новой строки перезапишите все ее(новой строки) содержимое в файл.
Example:
19847 Swim trunks, blue 159.00 12
198479 Swim trunks, black with printe173.00 17
19847983Snowboard jacket with reflecti10173.991234
Requirements:
1. The program should read a file name for CrUD operations from the console.
2. The Solution class should not use static variables.
3. When you run the program without arguments, the product list must remain unchanged.
4. When the program is run with the arguments "-c productName price quantity", a new line with
the corresponding product should be added to the end of the file.
5. The product must have the next id after the maximum id found in the file.
6. The format of the new product line must precisely match that format specified in the task.
7. The file streams must be closed.(mentor: The file input stream was not closed.)
*/