我的程序的目的是:
1)输入帐号并检查其是否存在于由帐号行组成的文本文件accs.txt中
2)输入文件的路径
3)读取文本文件的内容(如果存在输入),在每行后附加“ true”,否则添加“ false”,然后覆盖文件并给出输出。
我完成了大部分工作,但是不明白为什么FileWriter无法解决:
import java.io.*;
import java.util.*;
public class ReadFromFile2
{
public static void main(String[] args) throws IOException {
//create object of a text file
File file = new File("C:\\Users\\Artur\\Desktop\\accs.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
//ask for user account input
System.out.println("Enter your account number:");
Scanner input = new Scanner(System.in);
String account = input.nextLine();
//read the file and check if account exists
String st;
while ((st = br.readLine()) !=null) {
if(st.contains(account))
System.out.println("Found");
else System.out.println("Not found");
break;
}
//enter a filename accs.txt and the path
System.out.println("Enter file name:");
Scanner inputname = new Scanner(System.in);
String filename = input.nextLine();
System.out.println("Enter path for file accs:");
Scanner inputpath = new Scanner(System.in);
String path = input.nextLine();
//return path
File fileaccounts = new File(path + "\\" + filename);
System.out.println(fileaccounts);
//read results, if exists - true, if not - false, then write file
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
String fileContent = "accs.txt";
int lineNum = 0;
while ((st = br.readLine()) != null) {
if(st.contains(account))
st = st +"; true";
else st = st +"; false";
lineNum++;
System.out.println(st);
fileWriter.write(st);
//FileWriter fw = new FileWriter("C:\\Users\\Artur\\Desktop\\newfile.txt");
//fw.write(fileContent);
fw.close();
}
}
}
预期输出应为:
Enter your account number:
AA051245445454552117989
Found
Enter file name:
accs.txt
Enter path for file accs:
C:\Users\Artur\Desktop\\accs.txt
C:\Users\Artur\Desktop\accs.txt\accs.txt
LT647044001231465456; false
LT517044077788877777; false
LT227044077788877777; false
CC051245445454552117989; false
但是我修改了当前示例的代码,然后得到了
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
fileWriter cannot be resolved
at ReadFromFile2.main(ReadFromFile2.java:58)
PS:谢谢您的回答,这是我的一个小错误,但是我仍然无法使程序覆盖文件。有什么建议吗?
答案 0 :(得分:0)
您将FileWriter对象声明为fw
:
FileWriter fw = new FileWriter(file, true);
但是您尝试将其用作fileWriter
fileWriter.write(st);
您的代码中没有创建fileWriter
变量,因此会出现错误
答案 1 :(得分:0)
FileWriter fw = new FileWriter(file, true);
已定义,并且还定义了BufferedWriter:
BufferedWriter bw = new BufferedWriter(fw);
因此,不要调用fileWriter,而是执行以下操作:
bw.write(st);