首页 > 解决方案 > java将数字存储在文件中,并将用更大的数字替换数字,但如果文件为空,则不会存储

问题描述

我已经尝试使用 file.length 代码来扫描文件,如果它是空的,它将存储新号码。但是,如果文件为空,它不会将其存储在文件中。但如果新数字更大,它将替换文件中的数字。我试图让它存储文件中的第一个数字。

import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;

public class Tester {

    public static void main(String[] args)throws Exception{

        Scanner reader = new Scanner(System.in);  
        System.out.println("Enter a number: ");
        int n = reader.nextInt(); 
        reader.close();

        File file = new File("number.txt");
        Scanner input = new Scanner(file);
        int a = input.nextInt();

        if (n > a){
            PrintWriter output = new PrintWriter(file);
            output.println(n);
            output.close();
        } else if (file.length() == 0){
            PrintWriter output = new PrintWriter(file);
            output.println(n);
            output.close();
        }else { 
           System.out.println("File doesn't exist");
       }
    }
}

标签: javafile-ioreadfile

解决方案


我已经优化了你的代码。

首先,你应该提到number.txt文件的目录,在我的例子中,它是在包中创建的test,所以我提到了src/test/number.txt.

然后,我nullPrintWriter类赋值,以便稍后使用内部if语句。

Scanner input = new Scanner(file);Scanner在这种情况下,如果您不需要来自控制台的任何输入,则不需要使用第二个类,这取决于您。

while循环检查您的文件是否为空,如果为空,int a则为零,否则,int a从文件中获取数字。其余代码等于您的代码。

import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

public class Tester {
    public static void main(String[] args) throws Exception {

        Scanner reader = new Scanner(System.in);
        File file = new File("src/test/number.txt");
        PrintWriter output = null;

        System.out.println("Enter a number: ");
        int n = reader.nextInt();

        //you do not need to use a second Scanner class if you do not need any input
        Scanner input = new Scanner(file);
        int a = 0;

        //this is for reading a number of "number.txt" file
        while (input.hasNext()) {
            a = input.nextInt();
        }

        if (n > a) {
            output = new PrintWriter(file);
            output.println(n);
            output.close();
        } else if (file.length() == 0) {
            output = new PrintWriter(file);
            output.println(n);
            output.close();
        } else {
            System.out.println("File doesn't exist");
        }
    }
}

推荐阅读