关于传递两个字符串值并从TXT文件中移除的代码实现问题
Solution for Reading and Removing Facebook Credentials from a Text File
Got it, let's work through this step by step. Your goal is to read the first 3 username-password pairs from fbusers.txt, store them in your arrays, then remove those entries from the file. Here's how to complete and refine your code properly:
Complete Code Implementation
private static String[] fbuser; private static String[] fbpass; private static final int noOfUsers = 3; // Make this a constant for clarity public void insertFacebookDetails() throws InterruptedException { fbuser = new String[noOfUsers]; fbpass = new String[noOfUsers]; String userFileName = "fbusers.txt"; try { // Step 1: Read all lines from the file first FileReader fr = new FileReader(userFileName); BufferedReader br = new BufferedReader(fr); List<String> allLines = new ArrayList<>(); String line; while ((line = br.readLine()) != null) { allLines.add(line); } br.close(); fr.close(); // Step 2: Extract the first 'noOfUsers' pairs into your arrays for (int i = 0; i < noOfUsers && i < allLines.size(); i++) { // Assuming each line is formatted as "username password" (space-separated) String[] credentials = allLines.get(i).split(" ", 2); // Split into max 2 parts if (credentials.length == 2) { fbuser[i] = credentials[0]; fbpass[i] = credentials[1]; } else { // Handle invalid line format (optional but recommended) System.err.println("Invalid credential format on line: " + allLines.get(i)); fbuser[i] = null; fbpass[i] = null; } } // Step 3: Write the remaining lines back to the file (removing the first 3) PrintWriter pw = new PrintWriter(userFileName); for (int i = noOfUsers; i < allLines.size(); i++) { pw.println(allLines.get(i)); } pw.close(); // Optional: Verify the arrays are populated for (int i = 0; i < noOfUsers; i++) { System.out.println("User " + (i+1) + ": " + fbuser[i] + " | Pass: " + fbpass[i]); } } catch (IOException e) { e.printStackTrace(); // Add proper error handling here (e.g., alert user file not found) } }
Key Explanations:
- Reading All Lines First: We read every line from the file into a list first. This avoids conflicts from reading and writing to the same file simultaneously.
- Credential Parsing: The code assumes each line has a username and password separated by a space. If your file uses a different delimiter (like a comma), just adjust the
split(",", 2)part. - Removing Entries: By only writing lines starting from index
noOfUsersback to the file, we effectively delete the first 3 entries. - Resource Management: While the code uses explicit
close()calls, using try-with-resources (shown below) is better practice to auto-close streams and prevent leaks.
Improved Version with Try-With-Resources (Recommended)
Try-with-resources handles stream cleanup automatically, making your code more robust:
private static String[] fbuser; private static String[] fbpass; private static final int noOfUsers = 3; public void insertFacebookDetails() throws InterruptedException { fbuser = new String[noOfUsers]; fbpass = new String[noOfUsers]; String userFileName = "fbusers.txt"; try (FileReader fr = new FileReader(userFileName); BufferedReader br = new BufferedReader(fr)) { List<String> allLines = new ArrayList<>(); String line; while ((line = br.readLine()) != null) { allLines.add(line); } // Extract credentials for (int i = 0; i < noOfUsers && i < allLines.size(); i++) { String[] credentials = allLines.get(i).split(" ", 2); if (credentials.length == 2) { fbuser[i] = credentials[0]; fbpass[i] = credentials[1]; } else { System.err.println("Invalid line format: " + allLines.get(i)); fbuser[i] = null; fbpass[i] = null; } } // Write remaining lines back try (PrintWriter pw = new PrintWriter(userFileName)) { for (int i = noOfUsers; i < allLines.size(); i++) { pw.println(allLines.get(i)); } } } catch (IOException e) { e.printStackTrace(); // Handle exceptions appropriately (e.g., log, show error message) } }
Critical Notes:
- Security Risk: Storing plain-text passwords in a file is extremely insecure. Consider encrypting credentials or using a secure storage mechanism instead.
- File Path: Ensure
fbusers.txtis in the correct directory relative to your program's execution path. If not, use an absolute path (e.g.,C:/data/fbusers.txton Windows or/home/user/fbusers.txton Linux). - Edge Cases: The code checks
i < allLines.size()to avoid index out-of-bounds errors if the file has fewer than 3 entries.
内容的提问来源于stack exchange,提问作者javaprogrammer
相关产品推荐
相关产品推荐

