Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lesson8 task1 #7

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/com/javafordev/lesson8/task1/FileRunner.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.javafordev.lesson8.task1;

import java.io.IOException;
import java.nio.file.Path;

/**
* Задание 1: Дан файл со след строчками:
* Дата в формате (YYYY-MM-DD) - ФИО
* Пример: 2020-01-01 - Иванов Иван Иванович
* 2020-02-02 - Сидоров Сергей Петрович
* Нужно создать для каждой даты отдельную папку и положить внутрь данной папки файл со списком людей, соответтсвущих данной дате
*/
public class FileRunner {
public static void main(String[] args) throws IOException {
ilyalychkou marked this conversation as resolved.
Show resolved Hide resolved
String regexp = "([1-9]?[0-9]{3}-[0|1][0-9]-[0-3][0-9])\\s-\\s([А-Яа-яЁ-ё\\s]+)";
ilyalychkou marked this conversation as resolved.
Show resolved Hide resolved
Path path = Path.of(FileUtil.BASE_PATH_TO_FILE, "file.txt");
TextReader textReader = FileUtil.readDatesAndNamesFromFile(path, regexp);
FileUtil.createFoldersWithDateAsName(textReader);
FileUtil.writeNamesToFolderWithDate(textReader);
}
}
60 changes: 60 additions & 0 deletions src/com/javafordev/lesson8/task1/FileUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.javafordev.lesson8.task1;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtil {

public static final String BASE_PATH_TO_FILE = String.join(File.separator, "src", "com", "javafordev", "lesson8", "task1");

public static TextReader readDatesAndNamesFromFile(Path path, String regexp) {
List<String> dates = new ArrayList<>();
List<String> names = new ArrayList<>();
List<String> strings = new ArrayList<>();

Pattern pattern = Pattern.compile(regexp);

try {
strings = Files.readAllLines(path);
} catch (IOException e) {
e.printStackTrace();
}

for (String string : strings) {
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
dates.add(matcher.group(1));
names.add(matcher.group(2));
}
}
return new TextReader(dates, names);
}

public static void createFoldersWithDateAsName(TextReader textReader) {
Set<String> distinctDates = new HashSet<>(textReader.getDates());
for (String distinctDate : distinctDates) {
new File(String.join(File.separator, BASE_PATH_TO_FILE, distinctDate)).mkdir();
}
}

public static void writeNamesToFolderWithDate(TextReader textReader) throws IOException {
Set<String> distinctDates = new HashSet<>(textReader.getDates());
for (int i = 0; i < textReader.getDates().size(); i++) {
if (distinctDates.contains(textReader.getDates().get(i))) {
File file = new File(String.join(File.separator, FileUtil.BASE_PATH_TO_FILE, textReader.getDates().get(i), "names.txt"));
try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file, true))) {
fileWriter.append(textReader.getNames().get(i));
fileWriter.newLine();
}
}
}

}
}
30 changes: 30 additions & 0 deletions src/com/javafordev/lesson8/task1/TextReader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.javafordev.lesson8.task1;

import java.util.List;

public class TextReader {

private List<String> dates;
private List<String> names;

public TextReader(List<String> dates, List<String> names) {
this.dates = dates;
this.names = names;
}

public List<String> getDates() {
return dates;
}

public void setDates(List<String> dates) {
this.dates = dates;
}

public List<String> getNames() {
return names;
}

public void setNames(List<String> names) {
this.names = names;
}
}
9 changes: 9 additions & 0 deletions src/com/javafordev/lesson8/task1/file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
1999-01-01 - Иванов Иван Иванович
2020-01-01 - Стриж Ольга Еремеевна
2020-02-02 - Сидоров Сергей Петрович
2020-02-02 - Корзюк Ермак Борисович
2020-03-03 - Петров Петр Петрович
2020-03-03 - Лагутин Петр Иванович
2020-04-04 - Игорев Игорь Игоревич
2020-04-04 - Лычков Илья Валерьевия
2020-05-05 - Натальева Наталья Натальевна
38 changes: 38 additions & 0 deletions src/com/javafordev/lesson8/task2/FileUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.javafordev.lesson8.task2;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class FileUtil {

public static final String BASE_PATH_TO_FILE = String.join(File.separator, "src", "com", "javafordev", "lesson8", "task2");

public static List<String> readLinesFromFile(Path path) {
List<String> strings = new ArrayList<>();
try {
strings = Files.readAllLines(path);
} catch (IOException e) {
e.printStackTrace();
}
return strings;
}

public static List<String> replaceOddSpacesAndTabs(List<String > strings) {
return strings.stream()
.map(string -> string.replaceAll("\\s{2,}\\(", "("))
.map(string -> string.replaceAll("\\s{2,}new", " new"))
.map(string -> string.replaceAll("new\\s{2,}", "new "))
.map(string -> string.replaceAll("\\t{2,}", "\t"))
.map(string -> string.replaceAll("\\r{2,}", "")).collect(Collectors.toList());
}

public static void writeListToFile(Path result, List<String> strings) throws IOException {
Files.write(result, strings, Charset.defaultCharset());
}
}
29 changes: 29 additions & 0 deletions src/com/javafordev/lesson8/task2/JavaFileRunner.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.javafordev.lesson8.task2;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

/**
* Задание 2: Прочитать текст Java-программы и удалить из него все «лишние» пробелы
* и табуляции, оставив только необходимые для разделения операторов.
* При выполнении следующих задания для вывода результатов создавать файл средствами класса File. Новый файл должен заменить входной но с другим именем.
*/

public class JavaFileRunner {

public static void main(String[] args) throws IOException {

Path source = Path.of(String.join(File.separator, com.javafordev.lesson8.task2.FileUtil.BASE_PATH_TO_FILE, "Source.java"));
Path result = Path.of(String.join(File.separator, com.javafordev.lesson8.task2.FileUtil.BASE_PATH_TO_FILE, "Result.java"));

List<String> strings = FileUtil.readLinesFromFile(source);
List<String> list = FileUtil.replaceOddSpacesAndTabs(strings);
FileUtil.writeListToFile(result, list);

source.toFile().delete();
result.toFile().renameTo(source.toFile());
}
}

55 changes: 55 additions & 0 deletions src/com/javafordev/lesson8/task2/Source.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.javafordev.lesson8.task2;
import com.javafordev.lesson8.task1.FileUtil;
import com.javafordev.lesson8.task1.TextReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Source {
public static final String BASE_PATH_TO_FILE = String.join(File.separator, "src", "com", "javafordev", "lesson8", "task1");
public static TextReader readDatesAndNamesFromFile(Path path, String regexp) {
List<String> dates = new ArrayList<>();
List<String> names = new ArrayList<>();
List<String> strings = new ArrayList<>();
Pattern pattern = Pattern.compile(regexp);
try {
strings = Files.readAllLines(path);
} catch (IOException e) {
e.printStackTrace();
}
for (String string : strings) {
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
dates.add(matcher.group(1));
names.add(matcher.group(2));
}
}
return new TextReader(dates, names);
}
public static void createFoldersWithDateAsName(TextReader textReader) {
Set<String> distinctDates = new HashSet<>(textReader.getDates());
for (String distinctDate : distinctDates) {
new File(String.join(File.separator, BASE_PATH_TO_FILE, distinctDate)).mkdir();
}
}
public static void writeNamesToFolderWithDate(TextReader textReader) throws IOException {
Set<String> distinctDates = new HashSet<>(textReader.getDates());
for (int i = 0; i < textReader.getDates().size(); i++) {
if (distinctDates.contains(textReader.getDates().get(i))) {
File file = new File(String.join(File.separator, FileUtil.BASE_PATH_TO_FILE, textReader.getDates().get(i), "names.txt"));
try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file, true))) {
fileWriter.append(textReader.getNames().get(i));
fileWriter.newLine();
}
}
}
}
}
30 changes: 30 additions & 0 deletions src/com/javafordev/lesson8/task3/Person.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.javafordev.lesson8.task3;

import java.io.Serializable;

public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String firstName;
private int age;

public Person(String firstName, int age) {
this.firstName = firstName;
this.age = age;
}

public String getFirstName() {
return firstName;
}

public int getAge() {
return age;
}

@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", age=" + age +
'}';
}
}
23 changes: 23 additions & 0 deletions src/com/javafordev/lesson8/task3/PersonSerializationRunner.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.javafordev.lesson8.task3;

import java.io.*;
import java.nio.file.Path;

/**
* Задание 3:
* Нужно создать простейший класс с полями и методами. Провести с ним процессы сериализации и десериализации.
*/

public class PersonSerializationRunner {
public static void main(String[] args) throws IOException, ClassNotFoundException {

Path path = Path.of("src", "com", "javafordev", "lesson8", "task3", "person.txt");
PersonUtil.writeObject(path);
try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(path.toFile()))) {
Person deserializedPerson = (Person) objectInputStream.readObject();
System.out.println(deserializedPerson);
}
}

}

16 changes: 16 additions & 0 deletions src/com/javafordev/lesson8/task3/PersonUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.javafordev.lesson8.task3;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.file.Path;

public class PersonUtil {

public static void writeObject(Path path) throws IOException {
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(path.toFile()))) {
Person person = new Person("Stanislav", 22);
objectOutputStream.writeObject(person);
}
}
}
Binary file added src/com/javafordev/lesson8/task3/person.txt
Binary file not shown.
15 changes: 15 additions & 0 deletions src/com/javafordev/lesson8/task4/SaveText.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.javafordev.lesson8.task4;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SaveText {

String file();

String method();
}
11 changes: 11 additions & 0 deletions src/com/javafordev/lesson8/task4/Saver.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.javafordev.lesson8.task4;

import java.lang.reflect.InvocationTargetException;

public class Saver {

public static void executeSaving(TextContainer textContainer) throws NoSuchMethodException, NoSuchFieldException, InvocationTargetException, IllegalAccessException {
String method = textContainer.getClass().getDeclaredField("string").getAnnotation(SaveText.class).method();
textContainer.getClass().getMethod(method).invoke(textContainer);
}
}
Loading