From b614b0d0ce16482379267a116a6ea9b3a6ecb189 Mon Sep 17 00:00:00 2001 From: Eugene Fischer Date: Thu, 11 Jun 2020 13:48:53 -0500 Subject: [PATCH] rewritten to use streams --- Sorting/RandomNumberFileMaker.java | 34 ++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/Sorting/RandomNumberFileMaker.java b/Sorting/RandomNumberFileMaker.java index ab13f64..d79c143 100644 --- a/Sorting/RandomNumberFileMaker.java +++ b/Sorting/RandomNumberFileMaker.java @@ -1,9 +1,14 @@ package Sorting; -import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.io.BufferedWriter; +import java.util.Random; import java.io.IOException; -import java.io.FileWriter; -import java.lang.Math; +//import java.io.File; +//import java.io.FileWriter; +//import java.lang.Math; /** * This class will allow the user to make a file of random integers. @@ -24,6 +29,27 @@ public class RandomNumberFileMaker { max=M+1; } + //new version using streams and a try-with-resouces block + public void writeFile(){ + try(BufferedWriter writer = Files.newBufferedWriter(Path.of(filename), StandardOpenOption.CREATE_NEW)){ + Random random = new Random(); + random.ints(count, min, max+1) + .forEach(num -> + { + try{ + writer.write(Integer.toString(num)); writer.newLine(); + }catch (IOException ex){ + System.out.println("An error occurred."); + } + }); + }catch (IOException ex){ + System.out.println("Could not make new file named "+filename); + } + } + + + //previous version retained for reference. + /* public void writeFile(){ try{ File randomNumbers = new File(filename); @@ -42,6 +68,6 @@ public class RandomNumberFileMaker { }catch (IOException ex){ System.err.println(ex); } - } + }*/ } \ No newline at end of file