diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..0036b29a --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/Chapter01/P01_CountDuplicateCharacters/target/ +/Chapter01/P03_ReverseWords/target/ +/Chapter01/P05_CountVowelsAndConsonants/target/ +/Chapter01/P05_CountVowelsAndConsonants1/target/ +/Chapter01/P02_TextBlockDelimiters/target/ diff --git a/Chapter01/P01_CountDuplicateCharacters/src/modern/challenge/Strings.java b/Chapter01/P01_CountDuplicateCharacters/src/modern/challenge/Strings.java index 291b65e1..f52fbf06 100644 --- a/Chapter01/P01_CountDuplicateCharacters/src/modern/challenge/Strings.java +++ b/Chapter01/P01_CountDuplicateCharacters/src/modern/challenge/Strings.java @@ -51,7 +51,7 @@ public static Map countDuplicateCharactersVCP1(String str) { // or, like this (this code produce the same result as the commented code above int cp = str.codePointAt(i); String ch = String.valueOf(Character.toChars(cp)); - if(Character.charCount(cp) == 2) { // 2 means a suroggate pair + if(Character.charCount(cp) == 2) { // 2 means a surrogate pair i++; } diff --git a/Chapter01/README.md b/Chapter01/README.md index 52da82e9..c4381bb0 100644 --- a/Chapter01/README.md +++ b/Chapter01/README.md @@ -1,2 +1,2 @@ # Strings, numbers & math problems -This chapter includes 39 problems that involves strings, numbers and mathematical operations. The chapter starts with a bunch of classical problems for strings such as counting duplicates, reversing a string, removing whitespaces and so on and forth. The chapter continue with problems dedicated to numbers and mathematical operations such as summing two large numbers and operation overflow, comparing two unsigned numbers, compute the floor of a division and modulus, etc. Each problem is passed through several solutions including Java 8 functional style. Moreover, the chapter covers through problems the futures added in JDK 9, 10, 11 and 12. +This chapter includes 39 problems that involves strings, numbers and mathematical operations. The chapter starts with a bunch of classical problems for strings such as counting duplicates, reversing a string, removing whitespaces and so on and forth. The chapter continue with problems dedicated to numbers and mathematical operations such as summing two large numbers and operation overflow, comparing two unsigned numbers, compute the floor of a division and modulus, etc. Each problem is passed through several solutions including Java 8 functional style. Moreover, the chapter covers through problems the futures added in JDK 9, 10, 11 and 12. diff --git a/Chapter03/BONUS_1_ConvertYearMonthToDate/README.md b/Chapter03/BONUS_1_ConvertYearMonthToDate/README.md new file mode 100644 index 00000000..d654d971 --- /dev/null +++ b/Chapter03/BONUS_1_ConvertYearMonthToDate/README.md @@ -0,0 +1,2 @@ +# Converting `Date` to `YearMonth` +Write a program that converts an `Date` to `YearMonth` and vice-versa. diff --git a/Chapter03/BONUS_1_ConvertYearMonthToDate/pom.xml b/Chapter03/BONUS_1_ConvertYearMonthToDate/pom.xml new file mode 100644 index 00000000..fd4c512d --- /dev/null +++ b/Chapter03/BONUS_1_ConvertYearMonthToDate/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + com.app + BONUS_1_ConvertYearMonthToDate + 1.0-SNAPSHOT + jar + + UTF-8 + 13 + 13 + + BONUS_1_ConvertYearMonthToDate + \ No newline at end of file diff --git a/Chapter03/BONUS_1_ConvertYearMonthToDate/src/main/java/modern/challenge/Converters.java b/Chapter03/BONUS_1_ConvertYearMonthToDate/src/main/java/modern/challenge/Converters.java new file mode 100644 index 00000000..29ccc9c0 --- /dev/null +++ b/Chapter03/BONUS_1_ConvertYearMonthToDate/src/main/java/modern/challenge/Converters.java @@ -0,0 +1,33 @@ +package modern.challenge; + +import java.time.YearMonth; +import java.time.ZoneId; +import java.util.Date; + +public class Converters { + + private Converters() { + throw new AssertionError("Cannot be instantiatied"); + } + + public static YearMonth toYearMonth(Date date) { + + if (date == null) { + throw new IllegalArgumentException("The given date cannot be null"); + } + + return YearMonth.from(date.toInstant() + .atZone(ZoneId.systemDefault()) + .toLocalDate()); + } + + public static Date toDate(YearMonth ym) { + + if (ym == null) { + throw new IllegalArgumentException("The given year-month cannot be null"); + } + + return Date.from(ym.atDay(1) + .atStartOfDay(ZoneId.systemDefault()).toInstant()); + } +} diff --git a/Chapter03/BONUS_1_ConvertYearMonthToDate/src/main/java/modern/challenge/MainApplication.java b/Chapter03/BONUS_1_ConvertYearMonthToDate/src/main/java/modern/challenge/MainApplication.java new file mode 100644 index 00000000..f4b019e3 --- /dev/null +++ b/Chapter03/BONUS_1_ConvertYearMonthToDate/src/main/java/modern/challenge/MainApplication.java @@ -0,0 +1,13 @@ +package modern.challenge; + +import java.time.YearMonth; +import java.util.Date; + +public class MainApplication { + + public static void main(String[] args) { + + System.out.println("Date to YearMonth: " + Converters.toYearMonth(new Date())); + System.out.println("YearMonth to Date: " + Converters.toDate(YearMonth.now())); + } +} diff --git a/Chapter03/README.md b/Chapter03/README.md index 0a01b76a..9e889c5d 100644 --- a/Chapter03/README.md +++ b/Chapter03/README.md @@ -1,2 +1,2 @@ # Working with date and time -This chapter includes 20 problems that involves date and time. These problems are meant to cover a wide range of topics (e.g., converting, formatting, adding, subtracting, defining periods/durations, computing, etc) via **Date**, **Calendar**, **LocalDate**, **LocalTime**, **LocalDateTime**, **ZoneDateTime**, **OffsetDateTime**, **OffsetTime**, **Instant** and so on. +This chapter includes 20 problems that involves date and time. These problems are meant to cover a wide range of topics (e.g., converting, formatting, adding, subtracting, defining periods/durations, computing, etc) via **Date**, **Calendar**, **LocalDate**, **LocalTime**, **LocalDateTime**, **ZoneDateTime**, **OffsetDateTime**, **OffsetTime**, **Instant** and so on. diff --git a/Chapter05/BONUS_2_ConvertIterableToList/README.md b/Chapter05/BONUS_2_ConvertIterableToList/README.md new file mode 100644 index 00000000..cf84b634 --- /dev/null +++ b/Chapter05/BONUS_2_ConvertIterableToList/README.md @@ -0,0 +1,2 @@ +# Converting `Iterable` to `List` +Write a program that converts an `Iterable` to `List`. diff --git a/Chapter05/BONUS_2_ConvertIterableToList/pom.xml b/Chapter05/BONUS_2_ConvertIterableToList/pom.xml new file mode 100644 index 00000000..ef363031 --- /dev/null +++ b/Chapter05/BONUS_2_ConvertIterableToList/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + com.app + BONUS_2_ConvertIterableToList + 1.0-SNAPSHOT + jar + + UTF-8 + 13 + 13 + + BONUS_2_ConvertIterableToList + \ No newline at end of file diff --git a/Chapter05/BONUS_2_ConvertIterableToList/src/main/java/modern/challenge/Converters.java b/Chapter05/BONUS_2_ConvertIterableToList/src/main/java/modern/challenge/Converters.java new file mode 100644 index 00000000..8fb4844d --- /dev/null +++ b/Chapter05/BONUS_2_ConvertIterableToList/src/main/java/modern/challenge/Converters.java @@ -0,0 +1,97 @@ +package modern.challenge; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +public class Converters { + + private Converters() { + throw new AssertionError("Cannot be instantiatied"); + } + + public static List iterableToList1(Iterable iterable) { + + if (iterable == null) { + return Collections.emptyList(); + } + + List result = new ArrayList<>(); + iterable.forEach(result::add); + + return result; + } + + public static List iterableToList2(Iterable iterable) { + + if (iterable == null) { + return Collections.emptyList(); + } + + List result = StreamSupport.stream(iterable.spliterator(), false) + .collect(Collectors.toList()); + + return result; + } + + public static List iterableToList3(Iterable iterable) { + + if (iterable == null) { + return Collections.emptyList(); + } + + List result = new ArrayList<>(); + iterable.iterator().forEachRemaining(result::add); + + return result; + } + + public static List iterableToList4(Iterable iterable) { + + if (iterable == null) { + return Collections.emptyList(); + } + + List result + = StreamSupport.stream(Spliterators. + spliteratorUnknownSize(iterable.iterator(), Spliterator.ORDERED), false) + .collect(Collectors.toList()); + + return result; + } + + public static List iterableToList5(Iterable iterable) { + + if (iterable == null) { + return Collections.emptyList(); + } + + List result = new ArrayList<>(); + for (T elem : iterable) { + result.add(elem); + } + + return result; + } + + public static List iterableToList6(Iterable iterable) { + + if (iterable == null) { + return Collections.emptyList(); + } + + List result = new ArrayList<>(); + Iterator iterator = iterable.iterator(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + + return result; + } + +} diff --git a/Chapter05/BONUS_2_ConvertIterableToList/src/main/java/modern/challenge/MainApplication.java b/Chapter05/BONUS_2_ConvertIterableToList/src/main/java/modern/challenge/MainApplication.java new file mode 100644 index 00000000..a6252ed2 --- /dev/null +++ b/Chapter05/BONUS_2_ConvertIterableToList/src/main/java/modern/challenge/MainApplication.java @@ -0,0 +1,19 @@ +package modern.challenge; + +import java.util.Arrays; + +public class MainApplication { + + public static void main(String[] args) { + + // let's consider the next Iterable + Iterable iterable = Arrays.asList("ana", "george", "mark"); + + System.out.println("iterableToList1(): " + Converters.iterableToList1(iterable)); + System.out.println("iterableToList2(): " + Converters.iterableToList2(iterable)); + System.out.println("iterableToList3(): " + Converters.iterableToList3(iterable)); + System.out.println("iterableToList4(): " + Converters.iterableToList4(iterable)); + System.out.println("iterableToList5(): " + Converters.iterableToList5(iterable)); + System.out.println("iterableToList6(): " + Converters.iterableToList6(iterable)); + } +} diff --git a/Chapter05/BONUS_3_ConvertListVtoMapKListV/README.md b/Chapter05/BONUS_3_ConvertListVtoMapKListV/README.md new file mode 100644 index 00000000..9e830873 --- /dev/null +++ b/Chapter05/BONUS_3_ConvertListVtoMapKListV/README.md @@ -0,0 +1,3 @@ +# Convert `List` into `Map>` + +Write a program that converts `List` into `Map>`. diff --git a/Chapter05/BONUS_3_ConvertListVtoMapKListV/pom.xml b/Chapter05/BONUS_3_ConvertListVtoMapKListV/pom.xml new file mode 100644 index 00000000..bac0d2a9 --- /dev/null +++ b/Chapter05/BONUS_3_ConvertListVtoMapKListV/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + com.app + BONUS_3_ConvertListVtoMapKListV + 1.0-SNAPSHOT + jar + + UTF-8 + 13 + 13 + + BONUS_3_ConvertListVtoMapKListV + \ No newline at end of file diff --git a/Chapter05/BONUS_3_ConvertListVtoMapKListV/src/main/java/modern/challenge/Converters.java b/Chapter05/BONUS_3_ConvertListVtoMapKListV/src/main/java/modern/challenge/Converters.java new file mode 100644 index 00000000..562f7762 --- /dev/null +++ b/Chapter05/BONUS_3_ConvertListVtoMapKListV/src/main/java/modern/challenge/Converters.java @@ -0,0 +1,46 @@ +package modern.challenge; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +public class Converters { + + private Converters() { + throw new AssertionError("Cannot be instantiatied"); + } + + public static Map> toMap(List list) { + + if (list == null || list.isEmpty()) { + return Collections.emptyMap(); + } + + return list.stream().collect( + Collectors.groupingBy(String::length, + HashMap::new, Collectors.toCollection(ArrayList::new)) + ); + } + + @SuppressWarnings("unchecked") + public static , M extends Map> M toMap( + List list, Function c, Supplier ms, Supplier cs) { + + if (list == null || c == null || ms == null || cs == null + || list.isEmpty()) { + + throw new IllegalArgumentException("Non of the arguments can be null or empty"); + } + + return list.stream().collect( + Collectors.groupingBy(c, ms, Collectors.toCollection(cs)) + ); + } + +} \ No newline at end of file diff --git a/Chapter05/BONUS_3_ConvertListVtoMapKListV/src/main/java/modern/challenge/MainApplication.java b/Chapter05/BONUS_3_ConvertListVtoMapKListV/src/main/java/modern/challenge/MainApplication.java new file mode 100644 index 00000000..e8f5dc42 --- /dev/null +++ b/Chapter05/BONUS_3_ConvertListVtoMapKListV/src/main/java/modern/challenge/MainApplication.java @@ -0,0 +1,26 @@ +package modern.challenge; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; + +public class MainApplication { + + public static void main(String[] args) { + + /* Convert List into Map> */ + // consider this list + List names + = List.of("joana", "mark", "adela", "leo", "stan", "marius", "kely"); + + HashMap> result1 + = Converters.toMap(names, String::length, HashMap::new, ArrayList::new); + System.out.println("HashMap>: " + result1); + + LinkedHashMap> result2 + = Converters.toMap(names, String::length, LinkedHashMap::new, LinkedList::new); + System.out.println("LinkedHashMap>: " + result2); + } +} diff --git a/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/README.md b/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/README.md new file mode 100644 index 00000000..ae04a606 --- /dev/null +++ b/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/README.md @@ -0,0 +1,2 @@ +# Current directory +Write a program that return the current project root directory diff --git a/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/pom.xml b/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/pom.xml new file mode 100644 index 00000000..db2d1fc8 --- /dev/null +++ b/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/pom.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + com.app + BONUS_1_GetCurrentProjectRootDirectory + 1.0-SNAPSHOT + jar + + UTF-8 + 13 + 13 + + BONUS_1_GetCurrentProjectRootDirectory + \ No newline at end of file diff --git a/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/src/main/java/modern/challenge/MainApplication.java b/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/src/main/java/modern/challenge/MainApplication.java new file mode 100644 index 00000000..dca8ec4e --- /dev/null +++ b/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/src/main/java/modern/challenge/MainApplication.java @@ -0,0 +1,10 @@ +package modern.challenge; + +public class MainApplication { + + public static void main(String[] args) { + + System.out.println("The root directory of this project is:\n" + + Roots.getCurrentProjectRootDirectory()); + } +} diff --git a/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/src/main/java/modern/challenge/Roots.java b/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/src/main/java/modern/challenge/Roots.java new file mode 100644 index 00000000..82e892eb --- /dev/null +++ b/Chapter06/BONUS_1_GetCurrentProjectRootDirectory/src/main/java/modern/challenge/Roots.java @@ -0,0 +1,23 @@ +package modern.challenge; + +import java.nio.file.Path; +import java.nio.file.Paths; + +public class Roots { + + private Roots() { + throw new AssertionError("Cannot be instantiatied"); + } + + public static String getCurrentProjectRootDirectory() { + + String userDirectory = System.getProperty("user.dir"); + Path rootDirectory = Paths.get(".").normalize().toAbsolutePath(); + + if (rootDirectory.startsWith(userDirectory)) { + return rootDirectory.toString(); + } else { + throw new RuntimeException("Cannot find the current project root directory"); + } + } +} diff --git a/Chapter06/BONUS_2_CopyFileBenchmark/nb-configuration.xml b/Chapter06/BONUS_2_CopyFileBenchmark/nb-configuration.xml new file mode 100644 index 00000000..ec4540cb --- /dev/null +++ b/Chapter06/BONUS_2_CopyFileBenchmark/nb-configuration.xml @@ -0,0 +1,18 @@ + + + + + + none + + diff --git a/Chapter06/BONUS_2_CopyFileBenchmark/pom.xml b/Chapter06/BONUS_2_CopyFileBenchmark/pom.xml new file mode 100644 index 00000000..7eb5ecbf --- /dev/null +++ b/Chapter06/BONUS_2_CopyFileBenchmark/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + java.modern.challenge + BONUS_2_CopyFileBenchmark + 1.0 + jar + + UTF-8 + 20 + 20 + 3.8.0 + 1.35 + 3.10.1 + 3.1.0 + + BONUS_2_CopyFileBenchmark + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${oamp.version} + + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + + + + org.codehaus.mojo + exec-maven-plugin + ${ocm.version} + + + run-benchmarks + integration-test + + exec + + + test + java + + -classpath + + org.openjdk.jmh.Main + .* + + + + + + + + \ No newline at end of file diff --git a/Chapter06/BONUS_2_CopyFileBenchmark/rafa_copy/README.txt b/Chapter06/BONUS_2_CopyFileBenchmark/rafa_copy/README.txt new file mode 100644 index 00000000..ac6d0fc6 --- /dev/null +++ b/Chapter06/BONUS_2_CopyFileBenchmark/rafa_copy/README.txt @@ -0,0 +1 @@ +In this folder we copy the file used by benchmark. \ No newline at end of file diff --git a/Chapter06/BONUS_2_CopyFileBenchmark/rafa_org/Rafa Best Shots.mp4 b/Chapter06/BONUS_2_CopyFileBenchmark/rafa_org/Rafa Best Shots.mp4 new file mode 100644 index 00000000..166777eb Binary files /dev/null and b/Chapter06/BONUS_2_CopyFileBenchmark/rafa_org/Rafa Best Shots.mp4 differ diff --git a/Chapter06/BONUS_2_CopyFileBenchmark/results/benchmark.png b/Chapter06/BONUS_2_CopyFileBenchmark/results/benchmark.png new file mode 100644 index 00000000..e91d5bde Binary files /dev/null and b/Chapter06/BONUS_2_CopyFileBenchmark/results/benchmark.png differ diff --git a/Chapter06/BONUS_2_CopyFileBenchmark/src/main/java/modern/challenge/Main.java b/Chapter06/BONUS_2_CopyFileBenchmark/src/main/java/modern/challenge/Main.java new file mode 100644 index 00000000..3f8042d7 --- /dev/null +++ b/Chapter06/BONUS_2_CopyFileBenchmark/src/main/java/modern/challenge/Main.java @@ -0,0 +1,246 @@ +package modern.challenge; + +import java.nio.MappedByteBuffer; +import java.io.OutputStream; +import java.io.InputStream; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.EnumSet; +import static java.nio.file.LinkOption.NOFOLLOW_LINKS; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; + +@OutputTimeUnit(TimeUnit.SECONDS) +@BenchmarkMode(Mode.AverageTime) +@Fork(value = 1, warmups = 1) //, jvmArgsPrepend = {"-Djdk.net.usePlainSocketImpl=true"}) +@Measurement(iterations = 1, time = 1) +@State(Scope.Benchmark) +public class Main { + + private static final Path COPY_FROM = Paths.get("rafa_org/Rafa Best Shots.mp4"); + private static final Path COPY_TO = Paths.get("rafa_copy/"); + private static final int BUFFER_SIZE_KB = 4; + private static final int BUFFER_SIZE = BUFFER_SIZE_KB * 1024; + + private static final Random rnd = new Random(); + + @Benchmark + public static void fileChannelIndirectBuffer() { + + System.out.println("Using FileChannel and non-direct buffer ..."); + + Path copyTo = COPY_TO.resolve("Rafa Best Shots " + rnd.nextInt() + ".mp4"); + try (FileChannel fileChannel_from = (FileChannel.open(COPY_FROM, EnumSet.of(StandardOpenOption.READ))); + FileChannel fileChannel_to = (FileChannel.open(copyTo, EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)))) { + + // Allocate an non-direct ByteBuffer + ByteBuffer bytebuffer = ByteBuffer.allocate(BUFFER_SIZE); + + // Read data from file into ByteBuffer + while ((fileChannel_from.read(bytebuffer)) > 0) { + + //flip the buffer which set the limit to current position, and position to 0 + bytebuffer.flip(); + + //write data from ByteBuffer to file + fileChannel_to.write(bytebuffer); + + //for the next read + bytebuffer.clear(); + } + } catch (IOException ex) { + System.err.println(ex); + } + } + + @Benchmark + public static void fileChannelDirectBuffer() { + + System.out.println("Using FileChannel and direct buffer ..."); + + Path copyTo = COPY_TO.resolve("Rafa Best Shots " + rnd.nextInt() + ".mp4"); + try (FileChannel fileChannel_from = (FileChannel.open(COPY_FROM, EnumSet.of(StandardOpenOption.READ))); + FileChannel fileChannel_to = (FileChannel.open(copyTo, EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)))) { + + // Allocate an direct ByteBuffer + ByteBuffer bytebuffer = ByteBuffer.allocateDirect(BUFFER_SIZE); + + // Read data from file into ByteBuffer + while ((fileChannel_from.read(bytebuffer)) > 0) { + + //flip the buffer which set the limit to current position, and position to 0 + bytebuffer.flip(); + + //write data from ByteBuffer to file + fileChannel_to.write(bytebuffer); + + //for the next read + bytebuffer.clear(); + } + } catch (IOException ex) { + System.err.println(ex); + } + } + + @Benchmark + public static void fileChannelTransferTo() { + + System.out.println("Using FileChannel.transferTo method ..."); + + Path copyTo = COPY_TO.resolve("Rafa Best Shots " + rnd.nextInt() + ".mp4"); + try (FileChannel fileChannel_from = (FileChannel.open( + COPY_FROM, EnumSet.of(StandardOpenOption.READ))); + FileChannel fileChannel_to = (FileChannel.open(copyTo, EnumSet.of( + StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)))) { + + fileChannel_from.transferTo(0L, fileChannel_from.size(), fileChannel_to); + + } catch (IOException ex) { + System.err.println(ex); + } + } + + @Benchmark + public static void fileChannelTransferFrom() { + + System.out.println("Using FileChannel.transferFrom method ..."); + + Path copyTo = COPY_TO.resolve("Rafa Best Shots " + rnd.nextInt() + ".mp4"); + try (FileChannel fileChannel_from = (FileChannel.open( + COPY_FROM, EnumSet.of(StandardOpenOption.READ))); + FileChannel fileChannel_to = (FileChannel.open(copyTo, EnumSet.of( + StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)))) { + + fileChannel_to.transferFrom(fileChannel_from, 0L, (int) fileChannel_from.size()); + } catch (IOException ex) { + System.err.println(ex); + } + } + + @Benchmark + public static void fileChannelMap() { + + System.out.println("Using FileChannel.map method ..."); + + Path copyTo = COPY_TO.resolve("Rafa Best Shots " + rnd.nextInt() + ".mp4"); + try (FileChannel fileChannel_from = (FileChannel.open(COPY_FROM, EnumSet.of(StandardOpenOption.READ))); + FileChannel fileChannel_to = (FileChannel.open(copyTo, EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)))) { + + MappedByteBuffer buffer = fileChannel_from.map( + FileChannel.MapMode.READ_ONLY, 0, fileChannel_from.size()); + + fileChannel_to.write(buffer); + buffer.clear(); + + } catch (IOException ex) { + System.err.println(ex); + } + } + + @Benchmark + public static void bufferedStreamIO() { + + System.out.println("Using buffered streams and byte array ..."); + + Path copyTo = COPY_TO.resolve("Rafa Best Shots " + rnd.nextInt() + ".mp4"); + File inFileStr = COPY_FROM.toFile(); + File outFileStr = copyTo.toFile(); + + try (BufferedInputStream in = new BufferedInputStream( + new FileInputStream(inFileStr)); BufferedOutputStream out + = new BufferedOutputStream(new FileOutputStream(outFileStr))) { + + byte[] byteArray = new byte[BUFFER_SIZE]; + int bytesCount; + while ((bytesCount = in.read(byteArray)) != -1) { + out.write(byteArray, 0, bytesCount); + } + } catch (IOException ex) { + System.err.println(ex); + } + } + + @Benchmark + public static void bufferedStreamByteArray() { + + System.out.println("Using un-buffered streams and byte array ..."); + + Path copyTo = COPY_TO.resolve("Rafa Best Shots " + rnd.nextInt() + ".mp4"); + File inFileStr = COPY_FROM.toFile(); + File outFileStr = copyTo.toFile(); + + try (FileInputStream in = new FileInputStream(inFileStr); + FileOutputStream out = new FileOutputStream(outFileStr)) { + + byte[] byteArray = new byte[BUFFER_SIZE]; + int bytesCount; + while ((bytesCount = in.read(byteArray)) != -1) { + out.write(byteArray, 0, bytesCount); + } + } catch (IOException ex) { + System.err.println(ex); + } + } + + @Benchmark + public static void filesCopyPathToPath() { + + System.out.println("Using Files.copy (Path to Path) method ..."); + + Path copyTo = COPY_TO.resolve("Rafa Best Shots " + rnd.nextInt() + ".mp4"); + try { + Files.copy(COPY_FROM, copyTo, NOFOLLOW_LINKS); + } catch (IOException e) { + System.err.println(e); + } + } + + @Benchmark + public static void filesCopyIStreamToPath() { + + System.out.println("Using Files.copy (InputStream to Path) ..."); + + Path copyTo = COPY_TO.resolve("Rafa Best Shots " + rnd.nextInt() + ".mp4"); + try (InputStream is = new FileInputStream(COPY_FROM.toFile())) { + Files.copy(is, copyTo); + } catch (IOException e) { + System.err.println(e); + } + } + + @Benchmark + public static void filesCopyPathToOStream() { + + System.out.println("Using Files.copy (Path to OutputStream) ..."); + + Path copyTo = COPY_TO.resolve("Rafa Best Shots " + rnd.nextInt() + ".mp4"); + try (OutputStream os = new FileOutputStream(copyTo.toFile())) { + Files.copy(COPY_FROM, os); + } catch (IOException e) { + System.err.println(e); + } + } + + public static void main(String[] args) throws IOException { + + org.openjdk.jmh.Main.main(args); + } +} \ No newline at end of file diff --git a/Chapter06/README.md b/Chapter06/README.md index d66c8649..8eb91c42 100644 --- a/Chapter06/README.md +++ b/Chapter06/README.md @@ -1,3 +1,3 @@ -# Java I/O - Paths, files, buffers, scanning and formatting +# Java I/O - Paths, files, buffers, scanning and formatting This chapter includes 20 problems that involve Java I/O for files. From manipulating, walking and watching paths to streaming files and efficient ways for reading/writing text and binary files, we will cover a hand of problems that are a must in the arsenal of any Java developer. diff --git a/README.md b/README.md index 0f781169..aab522f6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ + + + # Java Coding Problems -Java Coding Problems +Java Coding Problems This is the code repository for [Java Coding Problems ](https://www.packtpub.com/programming/java-coding-problems?utm_source=github&utm_medium=repository&utm_campaign=), published by Packt. @@ -68,3 +71,7 @@ He is the author of several books, videos, and dozens of articles related to Jav [Click here](https://docs.google.com/forms/d/e/1FAIpQLSdy7dATC6QmEL81FIUuymZ0Wy9vH1jHkvpY57OiMeKGqib_Ow/viewform) if you have any feedback or suggestions. +### Download a free PDF + + If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
+

https://packt.link/free-ebook/9781789801415