所以我有一個包含用戶串列的檔案,格式如下:
michael:atbWfKL4etk4U:500:500:Michael Ferris:/home/michael:/bin/bash abigail:&i4KZ5wmac566:501:501:Abigail Smith:/home/abigail:/bin/tcsh
我需要做的只是從檔案中提取密碼,在這種情況下是:“ atbWfKL4etk4U ”和“ &i4KZ5wmac566 ”,并將它們存盤到一個陣列中。
這是我到目前為止所擁有的:
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();
}
uj5u.com熱心網友回復:
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();
}
如果您寧愿存盤用戶名和密碼(假設第一個令牌是用戶名),請創建 aMap而不是List.
Map<String, String> passwordMap = new HashMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] tokens = line.split(":");
passwordMap.put(tokens[0], tokens[1]);
}
uj5u.com熱心網友回復:
您可以使用 Scanner 物件逐行讀取檔案。然后,您使用另一個 Scanner 物件來讀取密碼。這是一個例子:
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();
uj5u.com熱心網友回復:
這看起來像一個典型的 CSV 型別檔案格式,因為檔案中的用戶數量未知,而且陣列不能動態增長,所以最好使用可以動態增長的 ArrayList,然后將該串列轉換為字串陣列,例如:
以下方法假設資料檔案中沒有標題行:
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()]);
}
你可以如何使用這樣的方法:
// 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);
}
如果您要針對包含您在帖子中提供的資料的檔案運行此代碼,您的控制臺視窗將顯示:
Enter the path of the file (c to cancel): --> userData.txt
Passwords from file:
====================
atbWfKL4etk4U
&i4KZ5wmac566
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/427712.html
下一篇:計算python檔案行數的問題
