我有一个程序,应该将内容写入文件,然后在程序末尾显示相同的文件。我有一个较小的测试程序,可以执行相同的操作,并且可以运行,但是原始程序不起作用。while( input != 5 ) { System.out.println(); System.out.print("Enter Selection (1-5): "); input = in.nextInt(); File myFile = new File ("password.txt"); PrintWriter outFile = new PrintWriter(myFile); if(input == 1 ) { System.out.print("Password Length (6 +): "); inputLength = in.nextInt(); if(inputLength >= 6) { for(int codeLength = 0; codeLength <= inputLength;) { randNum = random.nextInt(123); if(randNum >= 97 && randNum <= 122) { code+=(char)randNum; codeLength++; } else if(randNum >= 48 && randNum <= 57) { code+=(char)randNum; codeLength++; } } outFile.println(" " + codeNum + "\t" + code); outFile.close(); } else System.out.println("The password is too short"); } else if(input == 2) { System.out.print("Password Length (6 +): "); inputLength = in.nextInt(); if(inputLength >= 6) { for(int codeLength = 0; codeLength <= inputLength;) { randNum = random.nextInt(123); if(randNum >= 65 && randNum <= 90) { code+=(char)randNum; codeLength++; } else if(randNum >= 48 && randNum <= 57) { code+=(char)randNum; codeLength++; } } outFile.println(" " + codeNum + "\t" + code); outFile.close(); } else System.out.println("The password is too short"); } else if(input == 3 ) { System.out.print("Password Length (6 +): "); inputLength = in.nextInt(); if(inputLength >= 6) { for(int codeLength = 0; codeLength <= inputLength;) { randNum = random.nextInt(123); if(randNum >= 33 && randNum <= 47) { code+=(char)randNum; codeLength++; } else if(randNum >= 48 && randNum <= 57) { code+=(char)randNum; codeLength++; } } outFile.println(" " + codeNum + "\t" + code); outFile.close(); } else System.out.println("The password is too short"); } else if(input == 4 ) { System.out.print("Password Length (6 +): "); inputLength = in.nextInt(); if(inputLength >= 6) { for(int codeLength = 0; codeLength <= inputLength;) { randNum = random.nextInt(123); if(randNum >= 33 && randNum <= 126) { code+=(char)randNum; codeLength++; } else if(randNum >= 48 && randNum <= 57) { code+=(char)randNum; codeLength++; } } outFile.println(code); outFile.close(); } else System.out.println("The password is too short"); } else if(input == 5 ) { System.out.print("Thank you for using Fast Pass :)\n"); } else { System.out.println("Invalid option. Try again."); } System.out.println(); System.out.println("Here are your randomly generated codes:"); System.out.println(code); Scanner inFile = new Scanner("password.txt"); while( inFile.hasNext() ) { String file = inFile.next(); System.out.println(file); }应该发生的是显示类似的代码  1 --------  2 --------但是发生的是代码未写入文件,然后在运行时文件未打印 最佳答案 在您的PrintWriter构造函数中,使用true包装File参数后,将FileOutputStream作为第二个参数传递(将参数化的构造函数与File参数一起使用,将true用作)FileOutputStream构造函数中的true参数用于启用自动刷新,当您使用PrintWriter,println或printf之类的方法(但不是format时,则必须使用该方法)调用write方法)Here is the documentation for that
10-08 19:06