如何用Java实现按行号及数据类型替换文本文件内容?
Java Program to Modify Semicolon-Separated Text File
Here's a practical Java solution that lets you update specific fields in your semicolon-separated text file based on line number and data type:
Approach
- Read the File: Load all lines from the input file into a list for easy modification.
- Locate Target Line: Find the line using the provided line number (we’ll use 1-based numbering to match your file’s format).
- Split Line into Fields: Break the target line into individual components using semicolons (
;) as the delimiter. - Update the Specified Field: Replace the corresponding value based on the data type (name, phone, email).
- Overwrite the Original File: Write the modified list of lines back to the original file to save changes.
Complete Java Code
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class FileFieldUpdater { public static void main(String[] args) { // Get user input via console Scanner scanner = new Scanner(System.in); System.out.print("Enter full file path: "); String filePath = scanner.nextLine(); System.out.print("Enter line number to modify (1-based): "); int lineNumber = Integer.parseInt(scanner.nextLine()) - 1; // Convert to 0-based index for list access System.out.print("Enter data type to replace (name/phone/email): "); String dataType = scanner.nextLine().trim().toLowerCase(); System.out.print("Enter replacement string: "); String replacement = scanner.nextLine(); scanner.close(); try { // Read all lines from the file List<String> lines = new ArrayList<>(); BufferedReader reader = new BufferedReader(new FileReader(filePath)); String line; while ((line = reader.readLine()) != null) { lines.add(line); } reader.close(); // Validate line number if (lineNumber < 0 || lineNumber >= lines.size()) { System.err.println("Error: Invalid line number."); return; } // Split target line into fields String[] fields = lines.get(lineNumber).split(";"); if (fields.length != 5) { System.err.println("Error: Line format is invalid (expected 5 semicolon-separated fields)."); return; } // Map data type to field index int fieldIndex = -1; switch (dataType) { case "name": fieldIndex = 1; // Second field is the name (e.g., Mary Yeah) break; case "phone": fieldIndex = 3; // Fourth field is the phone number break; case "email": fieldIndex = 4; // Fifth field is the email address break; default: System.err.println("Error: Invalid data type. Choose name/phone/email."); return; } // Update the field and reconstruct the line fields[fieldIndex] = replacement; String updatedLine = String.join(";", fields); lines.set(lineNumber, updatedLine); // Write modified lines back to the file (overwrites original) BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); for (String l : lines) { writer.write(l); writer.newLine(); } writer.close(); System.out.println("File updated successfully!"); } catch (IOException e) { System.err.println("Error handling file: " + e.getMessage()); } catch (NumberFormatException e) { System.err.println("Error: Invalid line number (must be an integer)."); } } }
Key Details
- Line Numbering: The program uses 1-based numbering (so line 1 corresponds to the first entry in your file).
- Field Mapping:
nametargets the second field (index 1) in each line.phonetargets the fourth field (index 3).emailtargets the fifth field (index 4).
- Error Handling: Includes checks for invalid line numbers, malformed lines, unsupported data types, and file IO issues.
- Overwriting: Using
FileWriterwithout the append flag ensures the original file is replaced with the modified content.
How to Run
- Compile the code:
javac FileFieldUpdater.java - Execute the program:
java FileFieldUpdater - Follow the on-screen prompts to input the file path, line number, data type, and replacement string.
内容的提问来源于stack exchange,提问作者Lestat
相关产品推荐
相关产品推荐

