rewritten to use streams
This commit is contained in:
@@ -1,9 +1,14 @@
|
|||||||
package Sorting;
|
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.IOException;
|
||||||
import java.io.FileWriter;
|
//import java.io.File;
|
||||||
import java.lang.Math;
|
//import java.io.FileWriter;
|
||||||
|
//import java.lang.Math;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class will allow the user to make a file of random integers.
|
* This class will allow the user to make a file of random integers.
|
||||||
@@ -24,6 +29,27 @@ public class RandomNumberFileMaker {
|
|||||||
max=M+1;
|
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(){
|
public void writeFile(){
|
||||||
try{
|
try{
|
||||||
File randomNumbers = new File(filename);
|
File randomNumbers = new File(filename);
|
||||||
@@ -42,6 +68,6 @@ public class RandomNumberFileMaker {
|
|||||||
}catch (IOException ex){
|
}catch (IOException ex){
|
||||||
System.err.println(ex);
|
System.err.println(ex);
|
||||||
}
|
}
|
||||||
}
|
}*/
|
||||||
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user