gpt4 book ai didi

java - FileNotFoundException 解决方案?

转载 作者:太空宇宙 更新时间:2023-11-04 07:42:56 25 4
gpt4 key购买 nike

创建一个程序,将数据从数组列表写入文本文件,即使文件存在,我也遇到了这个 FileNotFoundException 。同时,我的数组中计算的数据不会写入其中。

这是我的代码:

 public static void payrollReadFromFile(String filename) {

// initializes br identifer as BufferedReader.
BufferedReader br = null;

payrolls.clear(); // removes all elements in arraylist employees

try {

br = new BufferedReader(new FileReader("payroll.txt"));
try {

String name;
double gincome, nincome, deduc, sss, pagibig,
phil = 0; // initialize identifiers

// reads each line through br identifier, and
stores it on
// temporary identifiers
// loop continues until null is encountered
while ((name = br.readLine()) != null) {

gincome = Double.parseDouble(br.readLine());
sss = Double.parseDouble(br.readLine());
pagibig =
Double.parseDouble(br.readLine());
phil = Double.parseDouble(br.readLine());
deduc = Double.parseDouble(br.readLine());
nincome =
Double.parseDouble(br.readLine());

// adds the data to payroll arraylist
payrolls.add(new Person( name, gincome,
sss, pagibig, phil,deduc, nincome));
}
} finally {
br.close(); // closes BufferedReader
}
} catch (IOException e) {
e.printStackTrace();
}
}



// method which writes data into parameter 'filename'
// uses PrintWriter and FileWriter
public static boolean payrollWriteToFile(String filename) {
boolean saved = false;
PrintWriter pw = null; // pw is a PrintWriter identifier

try {
// instantiate pw as PrintWriter, FileWriter
pw = new PrintWriter(new FileWriter("payroll.txt"));

try {

// for each loop. each data from payrolls is
written to parameter

for (Person payroll : payrolls) {

pw.println(payroll.getName());
pw.println(payroll.getGincome());
pw.println(payroll.getSss());
pw.println(payroll.getPagibig());
pw.println(payroll.getPhil());
pw.println(payroll.getDeduc());
pw.println(payroll.getNincome());


}
saved = true;
} finally {
pw.close();
}
} catch (IOException e) {

e.printStackTrace();
}
return saved;
}

最佳答案

您的文件打开语句:

   br = new BufferedReader(new FileReader("payroll.txt")); 

未使用您传递到该方法中的变量文件名。

您需要:

   br = new BufferedReader(new FileReader(filename)); 

您可能还想使用 File 对象。

关于java - FileNotFoundException 解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15775979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com