使用 Java 从另一个源文本文件修改或格式化后需要帮助来编写文本文件内容。假设我在源文本文件(text1.txt)中的文本内容下方。我已经在堆栈溢出中搜索了任何可能的重复项,但我找不到。所有现有的堆栈溢出问题都只与如何读写文本/文件有关。
********Total_Load_Start 应用的总负载(用户):8Total_Load_End *****************Avg_Start 8 个请求的平均响应时间(毫秒):2837 msAvg_End * *****************Success_start 加载 8 个请求的成功百分比:100.0 %Success_end ********************CPUPeak_Start 8个请求加载期间的cpu峰值使用率:1 %CPUPeak_End ****************** Pass_Start 8个请求加载期间的总成功响应:8 Pass_End***** *************Fail_Start 加载 8 个请求期间失败的响应总数:0 %Fail_End *********
现在我需要以以下格式读取和写入目标或输出文本文件 text2.txt:
Total_Load_Start The total load applied(Users) : 8
Avg_Start The Avg Response time(ms) for 8 requests : 2837 ms
Success_start The Success % for load of 8 requests : 100.0 %
CPUPeak_Start The Cpu peak % usage during the load of 8 requests :1 %
Pass_StartThe total succesful responses during the load of 8 requests :8
Fail_Start The total failed responses during the load of 8 requests :0 %
任何帮助,将不胜感激。
我试过这样:
static void modifyFile(String filePath, String oldString, String newString){
File fileToBeModified = new File(filePath);
String oldContent = "*";
BufferedReader reader = null;
FileWriter writer = null;
try{
reader = new BufferedReader(new FileReader(fileToBeModified));
String line = reader.readLine();
String [] separado = line.split("\\*");
while (separado != null) {
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
String newContent = oldContent.replaceAll(oldString, newString);
writer = new FileWriter(fileToBeModified);
writer.write(newContent);
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
TextFileReadWrite.modifyFile("C:\\Users\\raman\\Documents\\TestLoad_Final_Result.txt", "*", "");
System.out.println("done");
}
Path originalPath = Paths.get("file1.txt");
//Read the file content and add each line in list
List<String> orginalContentLines = Files.readAllLines(originalPath);
//Combine all lines to one string
String originalContent = orginalContentLines.stream().collect(Collectors.joining("\r\n"));
//Format the content by replacing * with new line
String newContent = originalContent.replaceAll("\\*+", "\r\n");
//Create the new file
Path newPath = Paths.get("file2.txt");
Files.createFile(newPath);
//Write to new file
Files.write(newPath, newContent.getBytes());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句