在使用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");
}
答案 0 :(得分:1)
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());