This commit is contained in:
2026-01-17 21:48:21 +03:00
parent 81223ec955
commit 4d53beef42
3 changed files with 98 additions and 41 deletions

View File

@@ -1,10 +1,5 @@
package com.filefilter; package com.filefilter;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import java.io.*; import java.io.*;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
@@ -13,34 +8,47 @@ import java.nio.file.Paths;
import java.nio.file.StandardOpenOption; import java.nio.file.StandardOpenOption;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
@Command(name = "file-filter", @Command(
name = "file-filter",
mixinStandardHelpOptions = true, mixinStandardHelpOptions = true,
version = "1.0", version = "1.0",
description = "Утилита фильтрации содержимого файлов по типам данных") description = "utility for filtering the content of files by data types"
)
public class FileFilterApp implements Runnable { public class FileFilterApp implements Runnable {
@Parameters(description = "Входные файлы для обработки") @Parameters(description = "Входные файлы для обработки")
private List<String> inputFiles = new ArrayList<>(); private List<String> inputFiles = new ArrayList<>();
@Option(names = {"-o", "--output"}, @Option(
description = "Путь для выходных файлов (по умолчанию: текущая директория)") names = { "-o", "--output" },
description = "Путь для выходных файлов (по умолчанию: текущая директория)"
)
private String outputPath = "."; private String outputPath = ".";
@Option(names = {"-p", "--prefix"}, @Option(
description = "Префикс имен выходных файлов") names = { "-p", "--prefix" },
description = "Префикс имен выходных файлов"
)
private String prefix = ""; private String prefix = "";
@Option(names = {"-a", "--append"}, @Option(
description = "Режим добавления в существующие файлы") names = { "-a", "--append" },
description = "Режим добавления в существующие файлы"
)
private boolean appendMode = false; private boolean appendMode = false;
@Option(names = {"-s", "--short-stats"}, @Option(
description = "Краткая статистика") names = { "-s", "--short-stats" },
description = "Краткая статистика"
)
private boolean shortStats = false; private boolean shortStats = false;
@Option(names = {"-f", "--full-stats"}, @Option(names = { "-f", "--full-stats" }, description = "Полная статистика")
description = "Полная статистика")
private boolean fullStats = false; private boolean fullStats = false;
private Statistics statistics; private Statistics statistics;
@@ -82,11 +90,18 @@ public class FileFilterApp implements Runnable {
} }
if (!Files.isReadable(filePath)) { if (!Files.isReadable(filePath)) {
System.err.println("Предупреждение: файл недоступен для чтения: " + filename); System.err.println(
"Предупреждение: файл недоступен для чтения: " + filename
);
return; return;
} }
try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) { try (
BufferedReader reader = Files.newBufferedReader(
filePath,
StandardCharsets.UTF_8
)
) {
String line; String line;
int lineNumber = 0; int lineNumber = 0;
@@ -95,7 +110,9 @@ public class FileFilterApp implements Runnable {
processLine(line, filename, lineNumber); processLine(line, filename, lineNumber);
} }
} catch (IOException e) { } catch (IOException e) {
System.err.println("Ошибка при чтении файла " + filename + ": " + e.getMessage()); System.err.println(
"Ошибка при чтении файла " + filename + ": " + e.getMessage()
);
} }
} }
@@ -113,29 +130,39 @@ public class FileFilterApp implements Runnable {
writerManager.writeInteger(intValue); writerManager.writeInteger(intValue);
statistics.addInteger(intValue); statistics.addInteger(intValue);
break; break;
case FLOAT: case FLOAT:
double floatValue = Double.parseDouble(line.trim()); double floatValue = Double.parseDouble(line.trim());
writerManager.writeFloat(floatValue); writerManager.writeFloat(floatValue);
statistics.addFloat(floatValue); statistics.addFloat(floatValue);
break; break;
case STRING: case STRING:
writerManager.writeString(line); writerManager.writeString(line);
statistics.addString(line); statistics.addString(line);
break; break;
} }
} catch (IOException e) { } catch (IOException e) {
System.err.println("Ошибка при записи данных из файла " + filename + System.err.println(
", строка " + lineNumber + ": " + e.getMessage()); "Ошибка при записи данных из файла " +
filename +
", строка " +
lineNumber +
": " +
e.getMessage()
);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
// Если парсинг не удался, считаем строкой // Если парсинг не удался, считаем строкой
try { try {
writerManager.writeString(line); writerManager.writeString(line);
statistics.addString(line); statistics.addString(line);
} catch (IOException ioException) { } catch (IOException ioException) {
System.err.println("Ошибка при записи строки из файла " + filename + System.err.println(
", строка " + lineNumber + ": " + ioException.getMessage()); "Ошибка при записи строки из файла " +
filename +
", строка " +
lineNumber +
": " +
ioException.getMessage()
);
} }
} }
} }
@@ -181,20 +208,30 @@ public class FileFilterApp implements Runnable {
System.out.println("=== Краткая статистика ==="); System.out.println("=== Краткая статистика ===");
if (statistics.getIntegerCount() > 0) { if (statistics.getIntegerCount() > 0) {
System.out.println("Целые числа: " + statistics.getIntegerCount() + " элементов"); System.out.println(
"Целые числа: " + statistics.getIntegerCount() + " элементов"
);
} }
if (statistics.getFloatCount() > 0) { if (statistics.getFloatCount() > 0) {
System.out.println("Вещественные числа: " + statistics.getFloatCount() + " элементов"); System.out.println(
"Вещественные числа: " +
statistics.getFloatCount() +
" элементов"
);
} }
if (statistics.getStringCount() > 0) { if (statistics.getStringCount() > 0) {
System.out.println("Строки: " + statistics.getStringCount() + " элементов"); System.out.println(
"Строки: " + statistics.getStringCount() + " элементов"
);
} }
if (statistics.getIntegerCount() == 0 && if (
statistics.getIntegerCount() == 0 &&
statistics.getFloatCount() == 0 && statistics.getFloatCount() == 0 &&
statistics.getStringCount() == 0) { statistics.getStringCount() == 0
) {
System.out.println("Данные не обработаны"); System.out.println("Данные не обработаны");
} }
} }
@@ -223,18 +260,26 @@ public class FileFilterApp implements Runnable {
if (statistics.getStringCount() > 0) { if (statistics.getStringCount() > 0) {
System.out.println("\nСтроки:"); System.out.println("\nСтроки:");
System.out.println(" Количество: " + statistics.getStringCount()); System.out.println(" Количество: " + statistics.getStringCount());
System.out.println(" Длина самой короткой: " + statistics.getStringMinLength()); System.out.println(
System.out.println(" Длина самой длинной: " + statistics.getStringMaxLength()); " Длина самой короткой: " + statistics.getStringMinLength()
);
System.out.println(
" Длина самой длинной: " + statistics.getStringMaxLength()
);
} }
if (statistics.getIntegerCount() == 0 && if (
statistics.getIntegerCount() == 0 &&
statistics.getFloatCount() == 0 && statistics.getFloatCount() == 0 &&
statistics.getStringCount() == 0) { statistics.getStringCount() == 0
) {
System.out.println("Данные не обработаны"); System.out.println("Данные не обработаны");
} }
} }
private enum DataType { private enum DataType {
INTEGER, FLOAT, STRING INTEGER,
FLOAT,
STRING,
} }
} }

View File

@@ -0,0 +1,8 @@
Lorem ipsum dolor sit amet
45
Пример
3.1415
consectetur adipiscing
-0.001
тестовое задание
100500

View File

@@ -0,0 +1,4 @@
Нормальная форма числа с плавающей запятой
1.528535047E-25
Long
1234567890123456789