需要帮助在Java中创建文件

时间:2018-07-10 19:28:28

标签: java

我需要创建一个文件,但是没有创建一个文件,而且我不知道它哪里出错了

这是我创建文件名的文本

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);

在这里使用文件名的参数

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();

这是我收到的错误文本:

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)

2 个答案:

答案 0 :(得分:2)

您提到未创建文件,但是在您的代码中我看不到应该创建文件的任何内容。

您是否期望新的File()为您在文件系统上创建文件?因为它不会,所以您需要File#createNewFile

答案 1 :(得分:0)

# Input array of length NOT multiple of width=3
In [99]: a
Out[99]: array([0, 3, 2, 4, 0, 2, 3, 1, 1, 6, 2])

In [100]: max_interval_slice(a, W=3)
Out[100]: array([3, 4, 3, 6])

# Input array of length multiple of width=3
In [95]: a = a[:9]

In [96]: max_interval_slice(a, W=3)
Out[96]: array([3, 4, 3])

“使用File.createNewFile()方法创建文件。此方法返回一个布尔值:如果成功创建了文件,则为true;如果文件已存在或由于某种原因操作失败,则为false。 -https://howtodoinjava.com/core-java/io/how-to-create-a-new-file-in-java/