【问题标题】:Find string and append text in java text file在 java 文本文件中查找字符串并附加文本
【发布时间】:2014-05-02 20:20:16
【问题描述】:

您好,对不好的事情感到抱歉。

这是一个文本文件

[TESTRESULT]
testdate=5/16/2013
testtime=20:03:00
operator=Jacob Poulsen
test_no=62495
axles_tested=2
[AXLE1RESULT]
fric_l=38
fric_r=51
p0_l=0
p0_r=0
fl=280
fr=300

所以我发现问题 首先找到字符串 ex:
[AXLE1RESULT] 之前的第二个附加文本
像这样

[TESTRESULT]
testdate=5/16/2013
testtime=20:03:00
operator=Jacob Poulsen
test_no=62495
axles_tested=2
[SomeText]
Something=0
Something=0
Something=0
[AXLE1RESULT]
fric_l=38
fric_r=51
p0_l=0
p0_r=0
fl=280
fr=300

我该怎么办???

【问题讨论】:

  • 我不知道你在问什么;但这些文件被格式化为 Windows INI 文件。也许stackoverflow.com/questions/190629/… 会有所帮助(ini4j 可以读取、解析和写入它们,并且可以让您轻松修改值)。

标签: java string file text filewriter


【解决方案1】:

最好从一个文件中读取并写入另一个文件。如果要附加一些文本检查是否出现并附加它。完成过程后,删除原始文件。

【讨论】:

  • 我不能写另一个文件,因为另一个程序正在使用这个文件
【解决方案2】:

这应该可以解决您的问题:

BufferedReader br= new BufferedReader(new FileReader("yourfilename.txt"));
String dataRow=null;
string tempText="";
while ( (dataRow= br.readLine()) dataRow != null){
    if(dataRow.equalsIgnoreCase("[AXLE1RESULT]"){
        tempText+="[SomeText]";
        tempText+=System.getProperty("line.separator");
        tempText+="Something=0";
        tempText+=System.getProperty("line.separator");
        tempText+="Something=0";
        tempText+=System.getProperty("line.separator");
        tempText+="Something=0";
        tempText+=System.getProperty("line.separator");
    }
    tempText+=dataRow;
    tempText+=System.getProperty("line.separator");
}

FileWriter writer = new FileWriter("yourfilename.txt");
writer.append(tempText);    
writer.flush();
writer.close();

【讨论】:

  • 如果要进行字符串连接,请使用 stringbuilder 或 stringbuffer
猜你喜欢
  • 2016-07-21
  • 2021-12-27
  • 1970-01-01
  • 2015-07-14
  • 2018-12-16
  • 2018-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多