Home > database >  Splitting Contents of a File
Splitting Contents of a File

Time:02-12

So I have a file with a list of users in the format like this:

michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash abigail:&i4KZ5wmac566:501:501:Abigail Smith:/home/abigail:/bin/tcsh

What I need to do is just extract the passwords from the file which in this case are: "atbWfKL4etk4U" and "&i4KZ5wmac566" and to store them into an array.

This is what I have so far:

public static void main(String[] args) throws IOException{
    
    // Create a scanner for keyboard input
    Scanner scan = new Scanner(System.in);
    
    // Prompt user to select a file to open
    System.out.print("Enter the path of the file: ");
    String filename = scan.nextLine();
    
    // Open the file
    File file = new File(filename);
    Scanner inputFile = new Scanner(file);
    
    // Create Array to store each user password in
    String[] passwords = {};
    

    
    // Close the file
    scan.close();
    inputFile.close();
    

}

CodePudding user response:

public static void main(String[] args) throws IOException{
    
    // Create a scanner for keyboard input
    Scanner scan = new Scanner(System.in);
    
    // Prompt user to select a file to open
    System.out.print("Enter the path of the file: ");
    String filename = scan.nextLine();
    
    // Open the file
    File file = new File(filename);
    Scanner inputFile = new Scanner(file);

    List<String> passwords = new ArrayList<>();
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        String password = line.split(":")[1];
        passwords.add(password);
    }
    // Close the file
    scan.close();
    inputFile.close();
}

If instead you rather store username and password (assuming the first token is the user name), create a Map instead of a List.

Map<String, String> passwordMap = new HashMap<>();
while (sc.hasNextLine()) {
   String line = sc.nextLine();
   String[] tokens = line.split(":");
    passwordMap.put(tokens[0], tokens[1]);
}

CodePudding user response:

You could read the file line by line using a Scanner object. Then, you use another Scanner object to read the password. Here's an example:

String input = "michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash";
Scanner s = new Scanner(input).useDelimiter(":");
s.next();  //skipping username
String password = s.next();
  • Related