Files
Tutoring-APCompSci/Sorting/RandomNumberFileMaker.java
2020-06-11 14:06:24 -05:00

73 lines
2.2 KiB
Java

package Sorting;
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.File;
//import java.io.FileWriter;
//import java.lang.Math;
/**
* This class will allow the user to make a file of random integers.
* The user will be able to select a file name, how many numbers are in the file,
* the minimum value generated, and the maximum value generated.
*/
public class RandomNumberFileMaker {
private String filename;
private int count;
private int min;
private int max;
public RandomNumberFileMaker(String f, int c, int m, int M){
filename=f;
count=c;
min=m;
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);
if(randomNumbers.createNewFile()==false){
System.out.println("File already exists.");
}
else{
FileWriter randomWriter = new FileWriter(randomNumbers);
for(int i=0;i<count;i++){
int rand = min + (int) (Math.random()*(max-min));
randomWriter.write(String.valueOf(rand));
randomWriter.write("\n");
}
randomWriter.close();
}
}catch (IOException ex){
System.err.println(ex);
}
}*/
}