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

Add files via upload #1016

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
22 changes: 22 additions & 0 deletions jv-read-from-file1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# jv-read-from-file
You are given a file that contains different words as well as punctuation.

You need to filter out only the words starting with `w`, and remove any punctuation if necessary.

The result should be returned as a naturally sorted array.
All words should be lower-case.

If the file does not contain the necessary words, return an empty array.

Examples:
```
"Width world Wide web"
Result: ["web", "wide", "width", "world"]

"WWW? Four-bedroom farmhouse in the countryside. Wave! All of the four double bedrooms are en suite."
Result: ["wave", "www"]
```

Hint: try to split Strings with a regular expression that includes whitespace and punctuation characters.
Here is a good [article](https://stackoverflow.com/questions/13225175/java-string-split-with-a-regex).
#### [Try to avoid these common mistakes, while solving task](https://mate-academy.github.io/jv-program-common-mistakes/java-core/builder-file/read-from-file.html)
55 changes: 55 additions & 0 deletions jv-read-from-file1/checklist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
### Common mistakes

#### Create variables with informative names.

Bad naming:
```java
BufferedReader br = new BufferedReader(new FileReader(fileName))
```

Good naming:
```java
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName))
```

#### Use constants where applicable.
If you have strange strings or numbers in the code it's better to declare them as constants.
The name of the constant should display this object's purpose.

Bad practice:
```java
public boolean startWithLetter(String word) {
return word.startsWith("d"); // why do we use 'd' here???
}
```

Good practice:
```java
private static final String SPECIFIED_CHARACTER = "d";

public boolean startWithLetter(String word) {
return word.startsWith(SPECIFIED_CHARACTER);
}
```
[Correct constant names](https://google.github.io/styleguide/javaguide.html#s5.2.4-constant-names)

#### Close all resources.
Connections, streams, files, and other classes that implement the `Closeable` or `AutoCloseable` interface,
needs to be closed after use. Furthermore, that close should be done in a `finally` block.
Preferably, when class implements `AutoCloseable`, resource should be created using "try-with-resources" pattern
and will be closed automatically.

#### Don't ignore exceptions.
Leaving empty catch block or `e.printStackTrace` here is a bad practice.
Better re-throw `RuntimeException` with original exception in the parameters:
```java
catch (Exception e) {
throw new RuntimeException(e);
}
```

#### Don't create redundant variables.
Let's make your code simple and easy to read. So better avoid using redundant variables.

#### Use System.lineSeparator() insted `\n`
[explanation](https://www.geeksforgeeks.org/system-lineseparator-method-in-java-with-examples/)
67 changes: 67 additions & 0 deletions jv-read-from-file1/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>mate-academy</groupId>
<artifactId>read-from-file</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<jdk.version>11</jdk.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.checkstyle.plugin.version>3.1.1</maven.checkstyle.plugin.version>
<maven.checkstyle.plugin.configLocation>
https://raw.githubusercontent.com/mate-academy/style-guides/master/java/checkstyle.xml
</maven.checkstyle.plugin.configLocation>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.1</version>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<configLocation>${maven.checkstyle.plugin.configLocation}</configLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
41 changes: 41 additions & 0 deletions jv-read-from-file1/src/main/java/core/basesyntax/FileWork.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package core.basesyntax;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class FileWork {

private static final String SEPARATOR_OF_WORDS = " ";

public String[] readFromFile(String fileName) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
int value = reader.read();
StringBuilder builder = new StringBuilder();
while (value != -1) {
builder.append((char) value);
value = reader.read();
}
String [] words = builder.toString().toLowerCase().split("\\W+");
StringBuilder resultBuilder = new StringBuilder();
for (String word : words) {
if (word.charAt(0) == 'w') {
resultBuilder.append(word).append(SEPARATOR_OF_WORDS);
}
}
if (resultBuilder.toString().isEmpty()) {
return new String[0];
}
String [] appropriateWords = resultBuilder.toString().trim().split(SEPARATOR_OF_WORDS);
Arrays.sort(appropriateWords);
return appropriateWords;
} catch (IOException e) {
throw new RuntimeException("Can't read file " + e);
} catch (StringIndexOutOfBoundsException e) {
return new String[0];
}
}

}
99 changes: 99 additions & 0 deletions jv-read-from-file1/src/test/java/core/basesyntax/FileWorkTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package core.basesyntax;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class FileWorkTest {
private static final String TEMP_DIRECTORY = System.getProperty("java.io.tmpdir") + "/";
private static final String EMPTY_FILE_NAME = TEMP_DIRECTORY + "test1";
private static final String SECOND_FILE_NAME = TEMP_DIRECTORY + "test2";
private static final String THIRD_FILE_NAME = TEMP_DIRECTORY + "test3";
private static final String FOURS_FILE_NAME = TEMP_DIRECTORY + "test4";
private static final String FIFTH_FILE_NAME = TEMP_DIRECTORY + "test5";

private static final String[] EMPTY_ARRAY_RESULT = new String[0];
private static final String[] RESULT_FROM_LOWER_CASE =
new String[]{"walk", "warm", "with", "with"};
private static final String[] RESULT_FROM_CAMEL_CASE =
new String[]{"wall", "wave", "width", "world", "www"};
private static final String[] RESULT_FROM_ADJACENT_WORDS_CASE =
new String[]{"was", "was", "whenever", "which", "which", "worse"};

@BeforeClass
public static void beforeClass() throws Exception{
Files.write(Path.of(EMPTY_FILE_NAME), "".getBytes(StandardCharsets.UTF_8));
Files.write(Path.of(SECOND_FILE_NAME), (
"Beautiful two-bedroom city flat five minutes' walk from the cathedral.\n" +
"Fully equipped kitchen, living room with a large sofa and chairs, big TV and balcony.\n" +
"The balcony has space for four people to sit and gets the sun in the mornings,\n" +
"and the flat is light and warm. The upstairs bedroom sleeps four people, with two double beds;\n" +
"the downstairs bedroom sleeps two in single beds.\n" +
"The flat is perfect for families and is near shops, bars and restaurants.\n").getBytes(StandardCharsets.UTF_8));
Files.write(Path.of(THIRD_FILE_NAME), (
"Four-bedroom farmhouse in the countryside. All of the four double bedrooms are en suite.\n" +
"Farm kitchen, tables and chairs outside. Great for groups of friends. The supermarket is half\n" +
"an hour by car and you can take a train from the village into the city. Escape from normal life\n" +
"for a few days.\n").getBytes(StandardCharsets.UTF_8));
Files.write(Path.of(FOURS_FILE_NAME), (
"WWW? Four-bedroom farmhouse in the countryside. Wave! All of the four double bedrooms are en suite.\n" +
"Farm kitchen, tables and chairs outside. Great for groups of friends. World and the supermarket is\n" +
"half an hour by car and you can take a train from wall the village into the city. Escape from normal\n" +
"life for a few days, width.\n").getBytes(StandardCharsets.UTF_8));
Files.write(Path.of(FIFTH_FILE_NAME), (
"Whenever I have gone there, there have been either so many\n" +
"people that I have not been able to see the pictures, which\n" +
"was dreadful, or so many pictures that I have not been able to see the people, which was\n" +
"worse. The Grosvenor is really the only place.\"\n").getBytes(StandardCharsets.UTF_8));
}

@Test
public void readFromEmptyFile() {
FileWork fileWork = new FileWork();
String[] actualResult = fileWork.readFromFile(EMPTY_FILE_NAME);
Assert.assertArrayEquals("Test failed! You should returned empty array.",
EMPTY_ARRAY_RESULT, actualResult);
}

@Test
public void getLowerCaseResultFromFile() {
FileWork fileWork = new FileWork();
String[] actualResult = fileWork.readFromFile(SECOND_FILE_NAME);
Assert.assertArrayEquals("Test failed! You should returned next array "
+ Arrays.toString(RESULT_FROM_LOWER_CASE) + " but you returned "
+ Arrays.toString(actualResult),
RESULT_FROM_LOWER_CASE, actualResult);
}

@Test
public void getCamelCaseResultFromFile() {
FileWork fileWork = new FileWork();
String[] actualResult = fileWork.readFromFile(FOURS_FILE_NAME);
Assert.assertArrayEquals("Test failed! You should returned next array "
+ Arrays.toString(RESULT_FROM_CAMEL_CASE) + " but you returned "
+ Arrays.toString(actualResult),
RESULT_FROM_CAMEL_CASE, actualResult);
}

@Test
public void getEmptyResultFromFile() {
FileWork fileWork = new FileWork();
String[] actualResult = fileWork.readFromFile(THIRD_FILE_NAME);
Assert.assertArrayEquals("Test failed! You should returned empty array.",
EMPTY_ARRAY_RESULT, actualResult);
}

@Test
public void getAdjacentWordsResultFromFile() {
FileWork fileWork = new FileWork();
String[] actualResult = fileWork.readFromFile(FIFTH_FILE_NAME);
Assert.assertArrayEquals("Test failed! You should returned next array "
+ Arrays.toString(RESULT_FROM_ADJACENT_WORDS_CASE) + " but you returned "
+ Arrays.toString(actualResult),
RESULT_FROM_ADJACENT_WORDS_CASE, actualResult);
}
}
3 changes: 3 additions & 0 deletions jv-read-from-file1/target/checkstyle-cachefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#Mon Oct 09 10:27:43 EEST 2023
/Users/mihail/githubprojects/jv-read-from-file1/src/main/java/core/basesyntax/FileWork.java=1696836447898
configuration*?=93620E16C42B1E083383B1E9D0BEA4FD5DCD7D93
Loading