Reputation: 29
I need a file to be created but one is not being created and I have no clue where it has gone wrong
This is where I have the text for the file name created
public class LetterGradeDisplayer {
public static void main(String[] args) {
LetterGradeConverter conv1 = new LetterGradeConverter("c://temp//grade1.txt", 6);
System.out.println("Contents: ");
System.out.println(conv1);
LetterGradeConverter conv2 = new LetterGradeConverter("c://temp//grade2.txt", 6);
System.out.println("Contents: ");
System.out.println(conv2);
This is where the argument for the file name is taken
public LetterGradeConverter(String fileName, int maxGrade) {
File file = new File(fileName);
int Grade[] = new int [maxGrade];
actualLength = maxGrade;
char LetterGradeList[] = new char [maxGrade];
int count = 0;
Scanner scan;
try {
scan = new Scanner(file);
while(scan.hasNextInt()) {
Grade[count] = scan.nextInt();
count++;
}
scan.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
GradeConverter();
This is the error text I am getting:
java.io.FileNotFoundException: c:\temp\grade1.txt (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(Unknown Source)
at java.base/java.io.FileInputStream.<init>(Unknown Source)
at java.base/java.util.Scanner.<init>(Unknown Source)
at LetterGrade.LetterGradeConverter.<init>(LetterGradeConverter.java:21)
at LetterGrade.LetterGradeDisplayer.main(LetterGradeDisplayer.java:7)
Exception in thread "main" java.lang.NullPointerException
at LetterGrade.LetterGradeConverter.GradeConverter(LetterGradeConverter.java:36)
at LetterGrade.LetterGradeConverter.<init>(LetterGradeConverter.java:32)
at LetterGrade.LetterGradeDisplayer.main(LetterGradeDisplayer.java:7)
Upvotes: 0
Views: 157
Reputation: 662
File file = new File("c://temp//testFile1.txt");
//Create the file
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
//Write Content
FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();
"Use File.createNewFile() method to create a file. This method returns a boolean value : true if the file is created successfully; false if the file is already exists or the operation failed for some reason." - https://howtodoinjava.com/core-java/io/how-to-create-a-new-file-in-java/
Upvotes: 0
Reputation: 2220
You mention a file not being created, but I see nothing in your code that SHOULD create a file.
Are you expecting new File() to create the file on the filesystem for you? Because it won't, for that you need File#createNewFile
Upvotes: 2