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

如何使用Java读取文本文件内容并格式化后写入另一个文本文件

Java: Read, Parse/Format, and Write Text Files (Structured Content)

Hey there! I get it—basic file read/write tutorials only take you so far, and your source file has that structured marker-based content that needs parsing and formatting. Let's walk through a complete solution tailored to your example.

Step 1: Read the Source File

First, let's read the content of text1.txt. For Java 11+, Files.readString() is super concise. If you're on an older version, we can use BufferedReader instead.

Example (Java 11+):

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

public class FileProcessor {
    public static void main(String[] args) {
        String sourceFilePath = "text1.txt";
        String targetFilePath = "formatted_output.txt";
        
        try {
            // Read entire file content into a string
            String content = Files.readString(Paths.get(sourceFilePath));
            
            // Step 2: Parse and format the content (we'll add this next)
            String formattedContent = parseAndFormatContent(content);
            
            // Step 3: Write to target file
            Files.writeString(Paths.get(targetFilePath), formattedContent);
            System.out.println("File processed successfully! Check " + targetFilePath);
            
        } catch (IOException e) {
            System.err.println("Error handling file: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Step 2: Parse and Format the Structured Content

Your source file uses markers like Total_Load_Start/Total_Load_End and Avg_Start—we'll use regular expressions to extract the relevant content between these markers, then clean it up into a readable format.

Add this method to the FileProcessor class:

private static String parseAndFormatContent(String rawContent) {
    StringBuilder formatted = new StringBuilder();
    
    // Extract Total Load info
    String totalLoadRegex = "Total_Load_Start (.*?)Total_Load_End";
    formatted.append(extractAndClean(rawContent, totalLoadRegex, "Total Load Applied (Users)"));
    
    // Extract Avg Response Time info (adjust regex if there's an Avg_End marker)
    String avgResponseRegex = "Avg_Start (.*?)"; 
    formatted.append(extractAndClean(rawContent, avgResponseRegex, "Average Response Time (ms)"));
    
    return formatted.toString().trim();
}

private static String extractAndClean(String content, String regex, String label) {
    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);
    java.util.regex.Matcher matcher = pattern.matcher(content);
    
    if (matcher.find()) {
        String rawValue = matcher.group(1).trim();
        // Clean up extra asterisks and whitespace
        rawValue = rawValue.replaceAll("\\*+", "").trim();
        return label + ": " + rawValue + "\n";
    }
    return label + ": Not found\n";
}

How This Works:

  • Regex targets the text between your start/end markers to pull out the meaningful data.
  • The extractAndClean method strips leftover asterisks and trims messy whitespace for a polished output.
  • If your actual file has an Avg_End marker, update the average response regex to Avg_Start (.*?)Avg_End for more precise extraction.

Step 3: Verify the Output

For your sample input:

********Total_Load_Start The total load applied(Users) : 8Total_Load_End *****************Avg_Start The Avg Response time(ms) for 8...

The formatted output in formatted_output.txt will look like:

Total Load Applied (Users): The total load applied(Users) : 8
Average Response Time (ms): The Avg Response time(ms) for 8...

If you want to extract just numeric values (like the 8 for total load), tweak the regex to target specific parts. For example:

String totalLoadRegex = "Total_Load_Start The total load applied\\(Users\\) : (\\d+)Total_Load_End";

Then use matcher.group(1) to get only the number 8.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:25:07