Integer.parseInt() stops working correctly when processing strings from a file, what could be the reason?

Just starting to learn the basics of Java, so do not judge strictly :) There is a file with the extension .txt. When you run the file with arguments, a new lot with a new id should be added to the file, which should be greater than the maximum of all existing ones in the file by 1. The contents of the file, for example:

19846__ _ Beach shorts blue__________159.00__12
198478__Black beach shorts with a pattern173.00__17
19847983Kurtka for snowboarders, razm10173. 991234

Id = 8 v characters, ProductName = 30 characters, price = 8 characters, quantity = 4 characters. There are no separating spaces between the lots. Each lot starts with a new line. The following code is available:

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class SolutionTask1827ArgsParamFile {

    public static void main(String[] args) throws Exception {
        // проверка
         args = new String[] {"-c", "Брюки кожаные", "1600.00", "25"};

        // программа должна работать если параметры введены, в остальных
        // случаях ничего не делаем
        if (args.length != 0) {

            // создаем поток для чтения имени файла
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

            // в переменную fileName записываем имя файла прочитанного с консоли
            String fileName = reader.readLine();

            // закрываем поток чтения имени файла
            reader.close();

            // создаем поток для чтения строк из файла и присваиваем ссылке reader этот
            // поток
            BufferedReader readerFile = new BufferedReader(new FileReader(fileName));

            // переменная, в которую поочередно читаем строки из файла
            String line;

            // Коллекция, в которую добавляем прочитанные строки
            List<String> priceList = new ArrayList<>();

            // переменная, в которую будем писать максимальный id
            int idMax = 0;

            // переменная, в которую будем заносить извлеченный из строки id и переведенный
            // в тип Integer
            int id;

            // читаем строки из файла и добавляем в коллекцию пока есть хоть одна строка
            while ((line = readerFile.readLine()) != null) {
                priceList.add(line);

                /* нужно найти максимальный id среди всех лотов в прайсе
                 т.к. известно, что id находится в начале строки и занимает всегда 8 символов
                 в строке, включая пробелы, поэтому берем из коллекции каждый элемент
                 представляющий собой строку лота и из этой строки выделяем подстроку
                 из первых восьми элементов, убираем лишние пробелы применив метод trim()
                 и переведя в Integer находи максимальный id
                */
                String lineCut = line.substring(0,8).trim();

                id = Integer.parseInt(lineCut);

                if (id > idMax) idMax = id;
            }

            // закрываем поток для чтения данных из файла
            reader.close();

            // закрываем поток для чтения из файла
            readerFile.close();

            // по условию id следующего лота должен быть на 1 больше максимально поэтому
            // инкрементируем максимальный id
            idMax++;

            /* следующим этапом нам необходимо добавить в уже имеющуюся коллекцию новую
             строку, представляющую собой лот из полученного нами idMax, предварительно
             переведенного в String, и в случае, если количество символов в нем меньше
             8, то добавлено недостающее кол-во пробелов, а также аргументов, которые
             были переданы при запуске программы args[1] - название из 30 символов,
             args[2] - цена из 8 символов, args[3] - количество из 4 символов. Если символов
             не хватает, то они так же должны быть добиты пробелами по аналогии с id
            */

            // переведем id из Integer в String и добавим недостающие пробелы до 8
            // символов
            String idString = String.valueOf(idMax);

            // переменная в которую запишем длину строки с id
            int length = idString.length();
            if (length < 8 ) {
                for (int i = 0; i < 8 - length ; i++) {
                    idString += " ";
                }
            }

            // добавим в наименование товара недостающие до 30 символов пробелы
            // если требуется
            String productName = args[1];
            if (productName.length() < 30) {
                for (int i = 0; i < 30 - args[1].length(); i++) {
                    productName += " ";
                }
            }

            // добавим в сумму недостающие до 8 символов пробелы, если требуется
            String price = args[2];
            if (price.length() < 8) {
                for (int j = 0; j < 8 - args[2].length(); j++) {
                    price += " ";
                }
            }

            // добавим в количество недостающие до 4 символов пробелы, если требуется
            String quantity = args[3];
            if (quantity.length() < 4) {
                for (int n = 0; n < 4 - args[3].length(); n++) {
                    quantity += " ";
                }
            }

            // соединяем все полученные данные позиции в одну строку и добавляем в
            // коллекцию
            priceList.add(idString + productName + price + quantity);

            if (args[0].equals("-c")) {

                // создаем поток для записи в файл
                BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));

                //записываем все элементы из коллекции в файл
                for (String e: priceList) {
                    // для записи с новой строки добавляем "\r\n"
                    if (e.equals(priceList.get(priceList.size()-1)))writer.write(e);
                    else writer.write(e + "\r\n");
                }

                // закрываем поток для записи
                writer.close();
            }
        }
    }
}

The code works, but! If you delete the contents of the file and enter the source data into it, or simply save the file by clicking "save", then when you try to run the file, the compiler throws the error Exception in thread "main" java. lang. NumberFormatException: For input string: "19846" pointing to the line with the code id = Integer.parseInt(lineCut); The problem is solved only after deleting the file and creating a new file with the original data. Also noticed that once the code stops to work correctly reading the substring from 0-th to 8-th symbol is not correct, because read is not 8 characters and 7. I.e. if the first id of the record to 8 characters, for example, 12345678, with the help of design substring(0, 8) 12345678 result is not as expected, and as it should be, and 1234567. What can happen to a file when you save what is it that stops parsing correctly? Please tell me what the problem may be, I really want to understand in order to avoid such problems when working with file texts in the future.

Thank you in advance!

Author: Сергей, 2020-09-05