diff --git a/.gitignore b/.gitignore index 53cee1b..31f3d21 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ *.zip *.tar.gz *.rar +*.iml # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* @@ -31,5 +32,6 @@ replay_pid* /.vscode/settings.json /.idea/vcs.xml /.idea/uiDesigner.xml -/out -/.idea \ No newline at end of file + +# Resources file +resources/* diff --git a/resources/introduction/info.txt b/resources/introduction/info.txt new file mode 100644 index 0000000..7d312f2 --- /dev/null +++ b/resources/introduction/info.txt @@ -0,0 +1 @@ +Hello some will come to check if I exists. \ No newline at end of file diff --git a/src/dates/exercises/Exercise1.java b/src/dates/exercises/Exercise1.java index 3cfb000..9a32658 100644 --- a/src/dates/exercises/Exercise1.java +++ b/src/dates/exercises/Exercise1.java @@ -1,6 +1,7 @@ package dates.exercises; import java.time.LocalDate; +import java.time.format.DateTimeFormatter; /** * Exercise 1: Basic Date and Time Operations @@ -16,16 +17,22 @@ */ public class Exercise1 { public static void main(String[] args) { - // TODO: Task 1 - Create your birthday - LocalDate birthday = null; // Replace with your birthday + // Task 1 - Create your birthday + LocalDate birthday = LocalDate.of(1970,10,16); - // TODO: Task 2 - Print formatted birthday message + // Task 2 - Print formatted birthday message + DateTimeFormatter f = DateTimeFormatter.ofPattern("EEEE dd MMMM Y"); + System.out.println("I'm born a " + birthday.format(f)); - // TODO: Task 3 - Check if leap year + // Task 3 - Check if leap year + String response = birthday.isLeapYear() ? "My birthday is a leap year.": "My birthday is NOT a leap year."; + System.out.println(response); - // TODO: Task 4 - Print day of year you were born - + // Task 4 - Print day of year you were born + System.out.println("I'm born the " + birthday.getDayOfYear() + "th day of the year " + birthday.getYear()); + System.out.println("It was a "+ birthday.getDayOfWeek() + "."); + } } diff --git a/src/dates/exercises/Exercise2.java b/src/dates/exercises/Exercise2.java index a50876d..6bc0f40 100644 --- a/src/dates/exercises/Exercise2.java +++ b/src/dates/exercises/Exercise2.java @@ -1,5 +1,9 @@ package dates.exercises; +import java.time.LocalDate; +import java.time.Period; +import java.time.temporal.TemporalAdjusters; + /** * Exercise 2: Date Arithmetic * @@ -17,28 +21,54 @@ */ public class Exercise2 { public static void main(String[] args) { - // TODO: Task 1 - Create today's date - - - // TODO: Task 2 - Sprint 1 deadline (7 days) - - - // TODO: Task 3 - Sprint 2 deadline (2 weeks) - - - // TODO: Task 4 - Mid-project review (1 month) - - - // TODO: Task 5 - Project end (3 months) - - - // TODO: Task 6 - Pre-planning phase (15 days before today) + // Task 1 - Create today's date + LocalDate today = LocalDate.now(); + System.out.println("Today: " + today); + + // Task 2 - Sprint 1 deadline (7 days) + LocalDate sp1DeadLine = today.plusDays(7); + System.out.println("Sprint 1 deadline: " + sp1DeadLine); + long nbDays = sp1DeadLine.toEpochDay() - today.toEpochDay(); + System.out.println("How many days before Sprint 1 deadline? " + nbDays + " days."); + System.out.println("=".repeat(20)); + + // Task 3 - Sprint 2 deadline (2 weeks) + LocalDate sp2DeadLine = today.plusWeeks(2); + System.out.println("Sprint 2 deadline: " + sp2DeadLine); + nbDays = sp2DeadLine.toEpochDay() - today.toEpochDay(); + System.out.println("How many days before Sprint 2 deadline? " + nbDays + " days."); + System.out.println("=".repeat(20)); + // Task 4 - Mid-project review (1 month) + LocalDate midReview = today.plusMonths(1); + System.out.println("Mid-project review: " + midReview); + nbDays = midReview.toEpochDay() - today.toEpochDay(); + System.out.println("How many days before the Mid-project review? " + nbDays + " days."); + System.out.println("=".repeat(20)); + + // Task 5 - Project end (3 months) + LocalDate endOfP = today.plusMonths(3); + System.out.println("Project end: " + endOfP); + nbDays =endOfP.toEpochDay() - today.toEpochDay(); + System.out.println("How many days before the end of the project? " + nbDays + " days."); + System.out.println("=".repeat(20)); - // TODO: Task 7 - 2 months and 10 days from today + // Task 6 - Pre-planning phase (15 days before today) + LocalDate preP = today.minusDays(15); + System.out.println("Pre-planning phase: " + preP); + System.out.println("How many days before?" + Period.between(today,preP).getDays() + " days."); + System.out.println("=".repeat(20)); + + // Task 7 - 2 months and 10 days from today + LocalDate holidays = today.plusMonths(2).plusDays(10); + System.out.println("My holidays: " + holidays); + nbDays = holidays.toEpochDay() - today.toEpochDay(); + System.out.println("How many days before my holidays? " + nbDays + " days."); // TODO: BONUS - Last day of next month (Hint: use TemporalAdjusters) + LocalDate bonus = today.plusMonths(1).with(TemporalAdjusters.lastDayOfMonth()); + System.out.println("Last day of next month: " + (bonus.getDayOfWeek()).toString().toLowerCase()); } } diff --git a/src/dates/exercises/Exercise3.java b/src/dates/exercises/Exercise3.java index 6fb560c..fe004e9 100644 --- a/src/dates/exercises/Exercise3.java +++ b/src/dates/exercises/Exercise3.java @@ -1,7 +1,10 @@ package dates.exercises; +import java.time.Duration; import java.time.LocalDate; import java.time.LocalTime; +import java.time.Period; +import java.time.temporal.TemporalAdjusters; /** * Exercise 3: Period and Duration Calculations @@ -19,36 +22,58 @@ */ public class Exercise3 { public static void main(String[] args) { - // TODO: Task 1 - Calculate your age - LocalDate birthday = LocalDate.of(2000, 1, 1); // Replace with your birthday + // Task 1 - Calculate your age + LocalDate birthday = LocalDate.of(1970, 02, 16); LocalDate today = LocalDate.now(); - - - // TODO: Task 2 - Create a method to calculate days between dates + int myAge = Period.between(birthday,today).getYears(); + System.out.println("My age: " + myAge); + + + // Task 2 - Create a method to calculate days between dates // Call it with two different dates and print the result - - - // TODO: Task 3 - Calculate working hours + LocalDate nextBirthday = LocalDate.of(2027, 02, 16); + + System.out.println("Number of days to wait before my birthday: " + calculateDaysBetween( today,nextBirthday)); + + // Task 3 - Calculate working hours LocalTime workStart = LocalTime.of(9, 0); - LocalTime workEnd = LocalTime.of(17, 30); - - - // TODO: Task 4 - Calculate actual working time (subtract 30 min lunch) - - - // TODO: Task 5 - Days until New Year 2027 + LocalTime workEnd = LocalTime.of(17, 0); + Duration workDay = Duration.between(workStart,workEnd); + System.out.println("workDay " + workDay.toHours()); + + // Task 4 - Calculate actual working time (subtract 30 min lunch) + long init = workDay.minusMinutes(30).getSeconds(); + long seconds = init % 60; + long temp = (init - seconds) / 60; + long minutes = temp % 60; + long hours = (temp - minutes) / 60; + if(seconds > 0){ + System.out.println("Actual working time: " + hours + ":" + minutes + ":" + seconds); + } + else{ + System.out.println("Actual working time: " + hours + ":" + minutes); + } + + // Task 5 - Days until New Year 2027 + LocalDate newY = today.with(TemporalAdjusters.lastDayOfYear()).plusDays(1); + long newYdays = newY.toEpochDay() - today.toEpochDay(); + System.out.println("Days until New Year 2027: " + newYdays); - // TODO: Task 6 - Add period to today + // Task 6 - Add period to today + Period toNY = Period.between(today, newY); + System.out.println("Add period to today: " + today.plus(toNY)); // TODO: BONUS - Calculate full weeks between birthday and today + long fullWeeks = Math.round( newYdays / 7); + System.out.println("Full weeks between birthday and today: " + fullWeeks ); } - // TODO: Task 2 - Implement this method + // Task 2 - Implement this method public static long calculateDaysBetween(LocalDate start, LocalDate end) { - // Your code here - return 0; + + return Math.abs(start.toEpochDay() - end.toEpochDay()); } } diff --git a/src/generics/exercises/Exercise1.java b/src/generics/exercises/Exercise1.java index 266418a..4cd42b1 100644 --- a/src/generics/exercises/Exercise1.java +++ b/src/generics/exercises/Exercise1.java @@ -1,5 +1,10 @@ package generics.exercises; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + /** * Exercise 1: Basic Generic Classes * @@ -23,61 +28,80 @@ * - Pair for ("age", 25) * - Swap it and print both pairs */ -public class Exercise1 -{ - public static void main(String[] args) - { - - Container stringContainer = new Container<>("Hello"); - Container intContainer = new Container<>(100); - Container boolContainer = new Container<>(true); - - System.out.println("String value: " + stringContainer.getValue()); - System.out.println("Integer value: " + intContainer.getValue()); - System.out.println("Boolean value: " + boolContainer.getValue()); - - - Pair agePair = new Pair<>("age", 25); - - System.out.println("Original Pair: " + - agePair.getKey() + " = " + agePair.getValue()); - - Pair swapped = agePair.swap(); - - System.out.println("Swapped Pair: " + swapped); +public class Exercise1 { + + public static void main(String[] args) { + System.out.println("=== Task 1 & 2: Container Class ===\n"); + + // Create Container instances and use them + Container s = new Container("I am a String"); + Container i = new Container(456); + Container l = new Container(LocalDate.now()); + Container a = new Container(new ArrayList<>()); + Container n = new Container(null); + + s.printValue(); + i.printValue(); + l.printValue(); + a.printValue(); + System.out.println("If this value null? " + s.isEmpty()); + System.out.println("If this value null? " + n.isEmpty()); + + System.out.println("\n=== Task 3 & 4: Pair Class ===\n"); + + // Create Paire instances, try swap() method. + Paire b = new Paire("Roberta", 24); + System.out.println("Before swap"); + System.out.println(b.toString()); + Paire c = b.swap(); + System.out.println("After swap"); + System.out.println(c.toString()); } } -class Container { +// Task 1 - Create Container class here +class Container{ - private T value; + T value; + public Container(T value){ + setValue(value); - public Container(T value) { - this.value = value; - } - - public T getValue() { - return value; } public void setValue(T value) { this.value = value; } - - public boolean isEmpty() { - return value == null; + public T getValue(){ + return this.value; + } + public void printValue(){ + System.out.println("Class of value: " + value.getClass()); + } + // method that returns true if value is null. + public boolean isEmpty(){ + return this.value == null; } } -class Pair { - private K key; - private V value; - - public Pair(K key, V value) { - this.key = key; - this.value = value; +// Task 3 - Create Pair class here +class Paire{ + K key; + V value; + public Paire(K key, V value){ + setKey(key); + setValue(value); + } + // SWAP METHOD + public Paire swap(){ + return new Paire(this.getValue(), this.getKey()); + } + // TOSTRING METHOD + @Override + public String toString() { + return "Key: " + this.getKey() + " Value: " + this.getValue(); } + // GETTERS public K getKey() { return key; } @@ -86,12 +110,12 @@ public V getValue() { return value; } - public Pair swap() { - return new Pair<>(value, key); + // SETTERS + public void setKey(K key){ + this.key = key; } - - @Override - public String toString() { - return "K: " + this.key + ", V: " + this.value; + public void setValue(V value){ + this.value = value; } -} \ No newline at end of file + +} diff --git a/src/generics/exercises/Exercise2.java b/src/generics/exercises/Exercise2.java index 9170a9d..96b223d 100644 --- a/src/generics/exercises/Exercise2.java +++ b/src/generics/exercises/Exercise2.java @@ -1,6 +1,7 @@ package generics.exercises; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -33,48 +34,189 @@ public class Exercise2 { public static void main(String[] args) { System.out.println("=== Task 1: Print Array ===\n"); - // TODO: Call printArray method + // Call printArray method + /* + * Write a generic method printArray(T[] array) that prints all elements + * Try it with String[], Integer[], and Double[] arrays + */ String[] words = {"Hello", "World", "Java"}; Integer[] numbers = {1, 2, 3, 4, 5}; - + printArray(words); + printArray(numbers); + System.out.println("\n=== Task 2: Reverse Array ===\n"); + /* + * Write a generic method reverse(T[] array) that returns a new array + * with elements in reverse order + * Try with different array types + * + */ // TODO: Call reverse method + reverse(words); + printArray(words); + reverse(numbers); + printArray(numbers); System.out.println("\n=== Task 3: Find Minimum ===\n"); - - // TODO: Call findMin method + /* + * Write a method findMin(List numbers) that returns + * the smallest number as a double + * Try with List and List + * + */ + // Call findMin method List integers = new ArrayList<>(); integers.add(10); integers.add(5); integers.add(20); integers.add(3); - - + integers.add(456); + integers.add(-30); + List doubles = new ArrayList<>(); + doubles.add(10.99); + doubles.add(5.67); + doubles.add(20.90); + doubles.add(3.76); + doubles.add(456.33); + doubles.add(-30.5); + System.out.println("Min integer = " + findMin(integers)); + System.out.println("Min double = " + findMin(doubles)); + System.out.println("\n=== Task 4: Calculator ===\n"); + /* + * Create a generic class Calculator + * Add add(), subtract(), multiply() methods that work with T + * Return results as double + * Try with Integer and Double + */ - // TODO: Create and use Calculator instances + // Create and use Calculator instances + Calculator calculator = new Calculator<>(); + System.out.printf("Add int => %.2f%n" , calculator.add(5,5,10)); + System.out.printf("Substract int => %.2f%n" , calculator.substract(5,5,10)); + System.out.printf("Multiply int => %.2f%n" , calculator.multiply(5,5,10)); + Calculator calculatorD = new Calculator<>(); + System.out.printf("Add double => %.2f%n" , calculatorD.add(5.5,5.5,10.99)); + System.out.printf("Substract double => %.2f%n" , calculatorD.substract(5.5,5.5,10.99)); + System.out.printf("Multiply double => %.2f%n" , calculatorD.multiply(5.5,5.5,10.99)); + System.out.println("\n=== Task 5: Count Greater Than ===\n"); + /* + * Write a method countGreaterThan(T[] array, T element) that counts + * how many elements are greater than the given element + * T must be Comparable + * Try with different types + */ - // TODO: Call countGreaterThan method + // Call countGreaterThan method + List greatersS = countGreaterThan(new String[]{"Babar", "Arseneisafuckman", "Zoe"}, "Babarissonet"); + + System.out.println("Size " + greatersS.size()); + System.out.println(greatersS); + + List greatersI = countGreaterThan(new Double[]{4.89,7.98,9.99}, 7.95); + + System.out.println("Size " + greatersI.size()); + System.out.println(greatersI); + + + + } - // TODO: Task 1 - Implement printArray method + // Task 1 - Implement printArray method + public static void printArray(T[] array){ + + for(int i=0; i< array.length; i ++){ + if(i == array.length - 1){ + System.out.print(array[i]); + } + else{ + System.out.print(array[i] + ", "); + } + } + System.out.println(); + + } - // TODO: Task 2 - Implement reverse method + // Task 2 - Implement reverse method + public static T[] reverse(T[] array){ + int left = 0; + int right =array.length -1; + while(left < right){ + T temp = array[left]; + array[left] = array[right]; + array[right] = temp; + left++; + right--; + } + + return array; + + } - // TODO: Task 3 - Implement findMin method + // Task 3 - Implement findMin method + public static double findMin(List numbers ){ + double min = (numbers.getFirst()).doubleValue(); + for(int i = 1; i< numbers.size(); i++){ + double d = (numbers.get(i)).doubleValue(); + if(min > d){ + min = d; + } + } + + return min; + } - // TODO: Task 5 - Implement countGreaterThan method + // Task 5 - Implement countGreaterThan method + public static >List countGreaterThan(T[] array,T element){ + List results = new ArrayList<>(); + for(T item:array){ + + if(item.compareTo(element) > 0 ){ + results.add(item); + } + + } + return results; + } } -// TODO: Task 4 - Create Calculator class here +// Task 4 - Create Calculator class here +class Calculator{ + // Add. + public double add(T ...args){ + double total=args[0].doubleValue(); + for (int i = 1; i < args.length; i++) { + total += (args[i]).doubleValue(); + } + return total; + } + // Substract. + public double substract(T ...args){ + double total=args[0].doubleValue(); + for (int i = 1; i < args.length; i++) { + total -= (args[i]).doubleValue(); + } + return total; + } + // Multiply. + public double multiply(T ...args){ + double total=args[0].doubleValue(); + for (int i = 1; i < args.length; i++) { + total *= (args[i]).doubleValue(); + } + return total; + } + +} diff --git a/src/generics/exercises/Exercise3.java b/src/generics/exercises/Exercise3.java index c89e3de..411a2a9 100644 --- a/src/generics/exercises/Exercise3.java +++ b/src/generics/exercises/Exercise3.java @@ -1,5 +1,6 @@ package generics.exercises; +import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -38,28 +39,43 @@ public class Exercise3 { public static void main(String[] args) { System.out.println("=== Task 1: Print Any List ===\n"); - - // TODO: Call printList with different types - - + List sList = Arrays.asList("Robert", "Stéphanie", "Norbert"); + List iList = Arrays.asList(555, 473,25); + List dateList = Arrays.asList(LocalDate.now(), LocalDate.now().plusDays(34), LocalDate.now().minusDays(56)); + printList(sList); + printList(iList); + printList(dateList); + System.out.println("\n=== Task 2: Sum Numbers ===\n"); - // TODO: Call sumList + // Call sumList List integers = Arrays.asList(1, 2, 3, 4, 5); List doubles = Arrays.asList(1.5, 2.5, 3.5); - - + System.out.println("\n=== Task 3: Add Integers ===\n"); - // TODO: Call addThreeIntegers with different list types + // Call addThreeIntegers with different list types List intList = new ArrayList<>(); List numList = new ArrayList<>(); List objList = new ArrayList<>(); - - + addThreeIntegers(intList); + addThreeIntegers(numList); + addThreeIntegers(objList); + printList(intList); + printList(numList); + printList(objList); + + System.out.println("\n=== Task 4: Copy Lists (PECS) ===\n"); // TODO: Demonstrate PECS with copy method + /* + 4. Write a method copy(List source, List dest) + * that copies all elements from source to destination + * - Demonstrate PECS principle + * - Try by copying List to List + * - Try by copying List to List + */ System.out.println("\n=== Task 5: Max of Two Lists ===\n"); @@ -73,13 +89,24 @@ public static void main(String[] args) { } - // TODO: Task 1 - Implement printList + // Task 1 - Implement printList + public static void printList(List list){ + for(Object item:list){ + System.out.println("printList: " + item); + } + System.out.println("=".repeat(25)); + } // TODO: Task 2 - Implement sumList - // TODO: Task 3 - Implement addThreeIntegers + // Task 3 - Implement addThreeIntegers + public static void addThreeIntegers(List list){ + List intToAdd = Arrays.asList(10, 20, 30); + list.addAll(intToAdd); + } + // TODO: Task 4 - Implement copy method diff --git a/src/introduction/examples/notes.txt b/src/introduction/examples/notes.txt new file mode 100644 index 0000000..4baf047 --- /dev/null +++ b/src/introduction/examples/notes.txt @@ -0,0 +1 @@ +Hello world. \ No newline at end of file diff --git a/src/introduction/exercises/Config.java b/src/introduction/exercises/Config.java new file mode 100644 index 0000000..739e3d7 --- /dev/null +++ b/src/introduction/exercises/Config.java @@ -0,0 +1,18 @@ +package introduction.exercises; + +import java.nio.file.Path; + +public class Config { + + public static Path getResPath(){ + return Path.of(".", + "HYFBE-java-week-5", + "resources"); + } + public static Path getIntroPath(){ + return Path.of(".", + "HYFBE-java-week-5", + "resources", + "introduction"); + } +} diff --git a/src/introduction/exercises/Exercise1.java b/src/introduction/exercises/Exercise1.java index 279884d..7f89ea9 100644 --- a/src/introduction/exercises/Exercise1.java +++ b/src/introduction/exercises/Exercise1.java @@ -10,10 +10,27 @@ package introduction.exercises; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; + public class Exercise1 { public static void main(String[] args) { + String path = Config.getIntroPath() + File.separator + "info.txt"; + File file = new File(path); + + if(file.exists()){ + System.out.println("Absolute path: " + file.getAbsolutePath()); + System.out.println("Size: " + file.length() + " bytes"); + System.out.println("Is readable: " +file.canRead()); + System.out.println("Is writable: " +file.canWrite()); + } + + else{ + System.out.println("File not found!"); + } } } diff --git a/src/introduction/exercises/Exercise2.java b/src/introduction/exercises/Exercise2.java index 4563919..91885ad 100644 --- a/src/introduction/exercises/Exercise2.java +++ b/src/introduction/exercises/Exercise2.java @@ -7,10 +7,35 @@ package introduction.exercises; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + public class Exercise2 { public static void main(String[] args) { + // Define a safe, OS-independent file path + String path = Config.getIntroPath() + File.separator + "students.txt"; + // Instance of a File Object. + File file = new File(path); + try { + // file.createNewFile() returns Boolean. + if(file.createNewFile()){ + System.out.println("File created successfully!"); + + System.out.println(file.getParentFile()); + } + else { + System.out.println("File already exists."); + System.out.println(file.delete()); + } + + } + catch (IOException e){ + System.out.println(e.getMessage()); + } + } } diff --git a/src/introduction/exercises/Exercise3.java b/src/introduction/exercises/Exercise3.java index 187fc60..0678d9a 100644 --- a/src/introduction/exercises/Exercise3.java +++ b/src/introduction/exercises/Exercise3.java @@ -9,10 +9,43 @@ package introduction.exercises; +import java.io.File; + public class Exercise3 { public static void main(String[] args) { + // 1. Create a File object pointing to the ("resources") directory. + String path = Config.getResPath().toString(); + File dir = new File(path); + if(dir.exists()){ + int[] result = listFiles(dir, new int[]{0,0}); + System.out.println(result[0] + " Directories " + result[1] + " Files "); + } + else{ + System.out.println("File not found!"); + } + + } + + public static int[] listFiles(File dir, int[] count){ + if(dir.isDirectory()){ + System.out.println("[DIR] " + dir.getName()); + File[] files = dir.listFiles(); + if(files != null){ + for(File f:files){ + if(f.isDirectory()){ + count[0] +=1; + listFiles(f, count); + } + else{ + System.out.println("[FILE] " + f.getParentFile().getName() + "." + f.getName()); + count[1] +=1; + } + } + } + } + return count; } } diff --git a/src/introduction/exercises/Exercise4.java b/src/introduction/exercises/Exercise4.java index 0ebf021..3ed7d72 100644 --- a/src/introduction/exercises/Exercise4.java +++ b/src/introduction/exercises/Exercise4.java @@ -9,7 +9,46 @@ package introduction.exercises; +import java.io.*; + public class Exercise4 { + static void main() { + + String path = Config.getIntroPath() + File.separator + "notes.txt"; + File file = new File(path); + String mess; + try{ + if(file.exists()){ + mess = "\nThis is an overwrite.\n"; + writeInFile(file, mess); + } + else{ + if(file.createNewFile()){ + mess = "Java I/O is powerful.\nStreams make reading and writing easier.\n"; + writeInFile(file, mess); + } + else{ + throw new IOException("File could not be created"); + } + + } + + } + catch(IOException e){ + System.out.println(e.getMessage()); + } + + } + public static void writeInFile(File file, String mess) throws IOException { + try(FileWriter writer = new FileWriter(file.getPath(), true)){ + writer.write(mess); + System.out.println("Data successfully written to file."); + } + catch (IOException e){ + System.out.println(e.getMessage()); + } + + }; } diff --git a/src/introduction/exercises/Exercise5.java b/src/introduction/exercises/Exercise5.java index 0134bee..2895b3f 100644 --- a/src/introduction/exercises/Exercise5.java +++ b/src/introduction/exercises/Exercise5.java @@ -8,10 +8,38 @@ package introduction.exercises; +import java.io.*; +import java.nio.file.Path; + public class Exercise5 { public static void main(String[] args) { + Path path = Config.getIntroPath(); + String sourcePath = path + File.separator + "source.jpg"; + String targetPath = path + File.separator + "copy.jpg"; + + if(copy(sourcePath, targetPath)){ + System.out.println("File copied successfully!"); + } + else { + System.out.println("Couille in ze potage!"); + } } + public static boolean copy(String inputPath, String outputPath){ + try( + FileInputStream input = new FileInputStream(inputPath); + FileOutputStream output = new FileOutputStream(outputPath)){ + int byteData; + while ((byteData = input.read()) != -1){ + output.write(byteData); + } + return true; + } + catch (IOException e){ + System.out.println(e.getMessage()); + return false; + } + } } diff --git a/src/introduction/exercises/Exercise6.java b/src/introduction/exercises/Exercise6.java index b866471..e016ca2 100644 --- a/src/introduction/exercises/Exercise6.java +++ b/src/introduction/exercises/Exercise6.java @@ -8,10 +8,49 @@ package introduction.exercises; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Path; +import java.util.Scanner; + public class Exercise6 { - public static void main(String[] args) - { + public static void main(String[] args) throws IOException { + Scanner scanner = new Scanner(System.in); + Path path = Config.getIntroPath(); + int nbSentences = 5; + System.out.print("What is your name? "); + String name = scanner.nextLine(); + String fileName = name.toLowerCase().replaceAll("[\\s ,]", "_"); + System.out.println("filename " + fileName); + // New File instance. + File file = new File(STR."\{path}\{File.separator}\{fileName}.txt"); + if(!file.exists()) { + if(file.createNewFile()){ + System.out.println(file.getName() + " created."); + } + } + System.out.println("File path: " + file.getAbsolutePath()); + System.out.print("How many sentence would do like to write? "); + // Set nbSentences. + if(scanner.hasNextInt()){ + nbSentences = scanner.nextInt(); + scanner.nextLine(); + } + try(FileWriter writer = new FileWriter(file.getPath(), true)){ + while(nbSentences > 0){ + System.out.print("Write a sentence: "); + String str = scanner.nextLine(); + writer.write(str + "\n"); + nbSentences--; + } + System.out.println(file.getName() + " was written."); + scanner.close(); + } + catch (IOException e){ + System.out.println("Write Error: " + e.getMessage()); + } } } diff --git a/src/reading/examples/Example3.java b/src/reading/examples/Example3.java index 6264ae8..4ae83ea 100644 --- a/src/reading/examples/Example3.java +++ b/src/reading/examples/Example3.java @@ -13,7 +13,7 @@ public class Example3 { public static void main(String[] args) { - String filePath = "resources" + File.separator + "notes.txt"; + String filePath = "resources" + File.separator + "introduction/examples/notes.txt"; int count = 0; try (BufferedReader reader = new BufferedReader(new FileReader(filePath)))