Строки заменяются, удаляются, однако валидатор ругается
package com.javarush.task.task18.task1828;
/*
Прайсы 2
*/
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Solution {
public static void main(String[] args) throws Exception {
String fileName = null;
// Считываем имена файлов
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
fileName = br.readLine();
} catch (IOException e) {
System.out.println("Не удалось считать имена файлов");
}
// Если входных данных нет, закрываем программу
if (args.length==0) return;
// Вызываем удаление строки
if (args[0].equals("-d")&&args.length==2){
deleteProduct(fileName,args[1]);
}
// Вызываем изменение строки
else if (args[0].equals("-u")&&args.length>=5){
//Собираем слова относящиеся к Product Name в одну строку
StringBuffer sb = new StringBuffer();
for (int i = 2; i < args.length-2; i++) {
sb.append(args[i]);
sb.append(" ");
}
String productName = sb.toString();
updateProduct(fileName,args[1],productName,args[args.length-2],args[args.length-1]);
}
}
// Метод форматирующий строку
private static String formatString(String string, int length){
if (string.length()>length)
return string.substring(0,length);
else if (string.length()<length){
return formatString((string+" "),length);
}else return string;
}
// Метод обновляющий строку
private static void updateProduct(String fileName, String idString, String productName, String price, String quantity){
try {
File file = new File(fileName);
File tempFile = File.createTempFile("CrUD", ".tmp"); // Временный файл
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
String line;
String idLine;
int id = Integer.parseInt(idString);
int tempId;
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tempFile))) {
while (bufferedReader.ready()) {
line = bufferedReader.readLine(); // Считываем строку из файла
if (!line.isEmpty()) {
idLine = line.substring(0, 8); // Выделяем id
tempId = Integer.parseInt(idLine.trim()); // Представляем id в числовом виде
if (tempId != id) {
bufferedWriter.write(line); // Если id в строке не совпадает, то перепысываем строку из
// исходного файла во временный
if (bufferedReader.ready()) bufferedWriter.newLine();
}else {
// Если id в строке совпадает, то пишем строку из аргументов
bufferedWriter.write(formatString(idString,8)+formatString(productName,30)+formatString(price,8)+formatString(quantity,4));
if(bufferedReader.ready()) bufferedWriter.newLine();
}
}
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
// Заменяем исходный файл временным
Files.copy(tempFile.toPath(),file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}catch (IOException e){
System.out.println("I/O error");
}
}
private static void deleteProduct(String fileName, String idString){
try {
// Все очень похоже на метод updateProduct
File file = new File(fileName);
File tempFile = File.createTempFile("CrUD", ".tmp");
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
String line, idLine;
int id = Integer.parseInt(idString);
int tempId;
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tempFile))) {
while (bufferedReader.ready()) {
line = bufferedReader.readLine();
if (!line.isEmpty()) {
idLine = line.substring(0, 8);
tempId = Integer.parseInt(idLine.trim());
if (tempId != id){
bufferedWriter.write(line);
if(bufferedReader.ready()) bufferedWriter.newLine();
}
}
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
Files.copy(tempFile.toPath(),file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}catch (IOException e){
System.out.println("I/O error");
}
}
}