-1

I am trying to get text from a .txt file and write it out in the System, but it is not working. My User.txt file has the format of

user:pass
user2:pass2
etc

I want to get the user and pass one at a time and show it in System.

Current the system for "Details" shows the path to the .txt file "username" shows "C" "password" shows "C" I am assuming the C comes starting the path file. I am not sure why it is not getting the text from the .txt file.

What am I doing wrong?

Also, it clears the whole .txt after the first iteration.

String username;
String password;
String details;

try {
  Scanner fileScanner = new Scanner(getDirectoryData() + "User.txt");
  details = fileScanner.nextLine();
  System.out.println(details);
  username = details.split(":")[0].split("@")[0];
  password = details.split(":")[0];

  System.out.println(username);
  System.out.println(password);

  FileWriter fileStream = new FileWriter(getDirectoryData() + "User.txt");
  BufferedWriter out = new BufferedWriter(fileStream);

  // sendMessage("INFO:BOT:" + username);

  while(fileScanner.hasNextLine()) {
    String next = fileScanner.nextLine();
    if(next.equals("\n")) {
      out.newLine();
    } else {
      out.write(next);
      out.newLine();
    }
  }

  out.close();
} catch (IOException e) {
  e.printStackTrace();
}
  • Incidentally, Stack Overflow isn't a forum, it's a Q&A site, which has very different conventions than a discussion forum. Please read the site [tour] to find out more about that. – EJoshuaS - Reinstate Monica Aug 30 '17 at 20:11

2 Answers2

1

So the problem you're having is that the Scanner is reading the String literally as getDirectoryData() + "User.txt" instead of reading the file you want to read. That's why you're getting the name of the file instead of the contents of the file.

Here's how you could modify your code to fix this:

    File file = new File(getDirectoryData() + "User.txt");
    Scanner fileScanner = new Scanner(file);
    details = fileScanner.nextLine();
    System.out.println(details);
0

If you are wanting to read all the entries from the file, probably you should do this and please change file directory as per your requirement.

public static void reader(){
        String details;

        try{
            File file = new File("file/User.txt");
            Scanner input = new Scanner(file);

            while(input.hasNextLine()){
                details = input.nextLine();
                System.out.println(" read file details : "+details);
            }
            input.close();

        }catch(Exception e){
            e.printStackTrace();
        }
    }
Mad-D
  • 4,046
  • 15
  • 46
  • 85