检查.txt文件是否存在。 FileWriter.exists方法无法正常工作

时间:2014-09-13 04:32:26

标签: java filewriter

解决!!!感谢手工让它工作。欣赏它!

我正在编写一个具有用户名和密码输入的程序。我试图检查用户是否存在文件,如果用户在创建用户名和密码时输入已存在的用户名。

.exists方法不起作用,我无法弄明白。错误找不到符号回来。我改变了一些东西,把事情搞砸了,并把它归结为一个错误。尝试使用循环以及if语句,但使用if只能让我犯一个错误。任何帮助都会很棒。

import java.util.Scanner;
import java.io.*;

class UserData 
{
  public static void main ( String[] args ) throws IOException
  {
  Scanner kb = new Scanner(System.in);

  System.out.println("Do you have an account? Yes or No: ");
  String answer = kb.next().trim();

  if ((answer.startsWith("N")) || (answer.startsWith("n")))
  {

System.out.println("Create user name: ");
String user = kb.next().trim();

String fileName = user + ".txt";
FileWriter userData = new FileWriter(fileName);

 if (userData.exists())
 {
   System.out.println("User already exists");
   System.out.println("Create user name: ");
   user = kb.next().trim();

   fileName = user + ".txt";
   userData = new FileWriter(fileName);
 }

System.out.println("Create Password: ");
String ps = kb.next().trim();

userData.write(user + " ");
userData.write(ps);
userData.close();


  }

  else if ((answer.startsWith("Y")) || (answer.startsWith("y")))
  {
System.out.println("Enter user name: ");
String user = kb.next().trim();

System.out.println("Enter Password: ");
String ps = kb.next().trim();

String fileName = user + ".txt";
Scanner inFile = new Scanner(new File(fileName));

String userName = inFile.next();
String password = inFile.next();

//     If ((userName != user) || (password != ps))
//     {
//       System.out.println("User Not Found");
//       System.out.println("Enter user name: ");
//       String user = kb.next().trim();
// 
//       System.out.println("Enter Password: ");
//       String ps = kb.next().trim();
//  
//       String fileName = user + ".txt";
//       Scanner inFile = new Scanner(new File(fileName));
//  
//       String userName = inFile.next();
//       String password = inFile.next();
//     }
//     else
//     {
   System.out.println("User Found");
//     }
}





}}

1 个答案:

答案 0 :(得分:3)

这里有编译错误:

FileWriter userData = new FileWriter(fileName);
if (userData.exists())

将其更改为:

File userDataFile = new File(fileName);
if (userDataFile.exists())

当然:

FileWriter userData = new FileWriter(userDataFile);
userData.write(user + " ");
userData.write(ps);
userData.close();

如果文件不存在,您可能正在查找错误的目录。尝试添加:

System.out.println(new File(fileName).getAbsolutePath());

并检查打印路径上的文件是否可用。