You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

  1. Read the File: Load all lines from the input file into a list for easy modification.
  2. Locate Target Line: Find the line using the provided line number (we’ll use 1-based numbering to match your file’s format).
  3. Split Line into Fields: Break the target line into individual components using semicolons (;) as the delimiter.
  4. Update the Specified Field: Replace the corresponding value based on the data type (name, phone, email).
  5. 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:
    • name targets the second field (index 1) in each line.
    • phone targets the fourth field (index 3).
    • email targets the fifth field (index 4).
  • Error Handling: Includes checks for invalid line numbers, malformed lines, unsupported data types, and file IO issues.
  • Overwriting: Using FileWriter without the append flag ensures the original file is replaced with the modified content.

How to Run

  1. Compile the code: javac FileFieldUpdater.java
  2. Execute the program: java FileFieldUpdater
  3. Follow the on-screen prompts to input the file path, line number, data type, and replacement string.

内容的提问来源于stack exchange,提问作者Lestat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:23:08