java - 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");
}
}
}
解决方案
我已经优化了你的代码。
首先,你应该提到number.txt
文件的目录,在我的例子中,它是在包中创建的test
,所以我提到了src/test/number.txt
.
然后,我null
为PrintWriter
类赋值,以便稍后使用内部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");
}
}
}
推荐阅读
- python - Python对值进行排序并根据唯一键对它们进行分组
- linux - 从远程网站下载 PDF 文件
- laravel - 如何将数据发送到 laravel voyager 管理面板中的自定义按钮
- c# - 如何在通知期间调用 XAMARIN iOS 中的 AVPlayer 而不是 30 秒的最大持续时间通知声音?
- c - GTK_TOGGLE_BUTTON() 宏期间的段错误。更改复选框状态后更改的指针值
- firebase - Firebase:FieldValue.arrayUnion 与对象
- ios - UICollectionView 在 iOS 11 上覆盖全屏
- r - 在 R 中进行子集化后保留列表元素名称
- react-native - 配置branch.io后,ios构建失败,抛出node_modules/react-native-branch/ios/Branch-SDK/Fabric/Fabric.h:没有这样的文件或目录
- firebase - Firestore 规则限制用户只能读/写他们的数据