当我第二次运行该程序时,我的 Record.txt
变空。
我认为我在文件阅读器中收到此错误,但我不知道该如何处理它。
如果你们能给我一个提示,我将不胜感激。
File file = new File("D:\\Program Files\\Oracle\\program\\Record.txt");
if (file.length() <= 0) {
try {
FileReader fr = new FileReader(
"D:\\Program Files\\Oracle\\program\\inventory.txt");
BufferedReader br = new BufferedReader(fr);
String datas = "";
while ((datas = br.readLine()) != null) {
String[] d = datas.split(",");
int a = Integer.parseInt(d[1]);
int b = Integer.parseInt(d[2]);
items.add(new list(d[0], a, b));
}
br.close();
fr.close();
} catch (IOException | NumberFormatException e) {
System.out.println("Error");
}
}
Iterator itemit = items.iterator();
try {
FileWriter fw = new FileWriter(
"D:\\Program Files\\Oracle\\program\\Record.txt");
BufferedWriter bw = new BufferedWriter(fw);
itemit = items.iterator();
while (itemit.hasNext()) {
list l = (list) itemit.next();
System.out.println(l.ingname + l.qty + l.ingid);
if (item1 == 1 && l.ingid == 100) {
l.qty = l.qty - item1qty;
}
if (item2 == 1 && l.ingid == 200) {
l.qty = l.qty - item2qty;
}
bw.write(l.ingname + ":" + l.qty + ":" + l.ingid);
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException e) {
System.out.println("Error");
}
else{
try{
FileReader fr = new FileReader("D:\\Program Files\\Oracle\\program\\Record.txt");
BufferedReader br = new BufferedReader(fr);
String datas = "";
//System.out.println(file.length());
while((datas = br.readLine()) != null){
String[] d = datas.split(",");
int x = Integer.parseInt(d[1]);
items.add(new list(d[0],x));
}
br.close();
fr.close();
}catch(IOException | NumberFormatException e){
System.out.println("Error");
}
}
最佳答案
从您提供的代码部分来看,如果Record.txt
文件为空。如果它不为空(例如第二次运行程序时),items
可能为空,因此 Record.txt
的内容将被覆盖。
目前您的代码如下所示
if (Record.txt file is emtpy) {
read inventory file into items
}
write items to record file
// where is the corresponding if?!
else {
read Record.txt file
}
大概应该是这样的
if (Record.txt file is emtpy) {
read inventory file into items
write items to record file
}
else {
read Record.txt file
}
关于java - 文件处理在第二次使用后删除记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53389965/