'Splitting Contents of a File
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();
}
Solution 1:[1]
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]);
}
Solution 2:[2]
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();
Solution 3:[3]
This looks like a typical CSV type file format and because there is an unknown number of Users in the file and the fact that arrays can not dynamically grow it's a good idea to utilize an ArrayList which can grow dynamically and then convert that list to a String array, for example:
The following method assumes there is No Header Line within the data file:
public static String[] getPasswordsFromFile(String filePath) {
List<String> passwordsList = new ArrayList<>();
File file = new File(filePath);
try (Scanner reader = new Scanner(file)) {
String line = "";
while (reader.hasNextLine()) {
line = reader.nextLine().trim();
// Skip blank lines (if any).
if (line.isEmpty()) {
continue;
}
/* Split out the password from the file data line:
The Regular Expression (RegEx) below splits each
encountered file line based on the Colon(:) delimiter
but also handles any possible whitespaces before
or after that delimiter: */
String linePassword = line.split("\\s*\\:\\s*")[1];
// If there is no password there then apply "N/A":
if (linePassword.isEmpty()) {
linePassword = "N/A";
}
// Add the password to the List
passwordsList.add(linePassword);
}
}
catch (FileNotFoundException ex) {
// Handle the exception (if any) the way you like...
System.err.println(ex.getMessage());
}
// Convert the List<String> to String[] Array and return:
return passwordsList.toArray(new String[passwordsList.size()]);
}
How you might use a method like this:
// Create a scanner object for keyboard input
Scanner userInput = new Scanner(System.in);
// Prompt user to select a file to open with validation:
String fileName = "";
// -----------------------------------
while (fileName.isEmpty()) {
System.out.print("Enter the path of the file (c to cancel): --> ");
fileName = userInput.nextLine();
if (fileName.equalsIgnoreCase("c")) {
System.out.println("Process Canceled! Quiting.");
System.exit(0);
}
if (!new File(fileName).exists()) {
System.out.println("Invalid Entry! Try again...\n");
fileName = "";
}
}
// -----------------------------------
/* OR - you could have........
// -----------------------------------
javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new File("").getAbsolutePath());
fc.showDialog(new JDialog(), "get Passwords");
if (fc.getSelectedFile() != null) {
fileName = fc.getSelectedFile().getAbsolutePath();
}
else {
System.out.println("Process Canceled! Quiting.");
System.exit(0);
}
// -----------------------------------
*/
// Get the Passwords from file:
String[] passwords = getPasswordsFromFile("UserData.txt");
// Display the Passwords retrieved:
System.out.println();
System.out.println("Passwords from file:");
System.out.println("====================");
for (String str : passwords) {
System.out.println(str);
}
If you were to run this code against a file which contains the data you provided within your post,your console window will diplay:
Enter the path of the file (c to cancel): --> userData.txt
Passwords from file:
====================
atbWfKL4etk4U
&i4KZ5wmac566
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hfontanez |
| Solution 2 | Cheng Thao |
| Solution 3 | DevilsHnd |
