我程序的目的是:
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)
我程序的目的是:1)输入帐号,并检查它是否存在于坚持帐号行的文本文件accs.txt中2)输入文件的路径3)读取...的内容
您将FileWriter对象声明为fw
: