我想要' name'和'代码'要插入到log.txt文件中,但是如果我运行此程序只将名称结果插入到.txt文件中,我看不到名称下附加的代码结果。如果我做System.outprintln(name)& System.outprintln(code)我在控制台中打印结果但是没有插入文件中。有人告诉我我做错了什么?
Scanner sc = new Scanner(file, "UTF-8");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("text1")) {
String[] splits = line.split("=");
String name = splits[2];
for (int i = 0; i < name.length(); i++) {
out.println(name);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
String code = splits[2];
for (int i = 0; i < code.length(); i++) {
out.println(code);
}
}
out.close()
}
文件看起来像:
Name=111111111
Code=333,5555
Category-Warranty
Name=2222222
Code=111,22
Category-Warranty
答案 0 :(得分:0)
看看这段代码。这对你有用吗?
name
您的代码中存在一些问题:
code
和close()
。PrintWriter
while
<table name="transactions">
<row>
<col name="id">1</col>
<col name="amount">2673.9</col>
<col name="created_date">2014-10-19</col>
<col name="display_date">2014-04-22</col>
<col name="cat_id">13</col>
<col name="note">Initial Balance</col>
//other col tags
</row>
<row>
...
</row>
</table>
循环中的IEnumerable<XElement> rows =
from el in root.Elements("row")
where (string)el.Element("col").Attribute("name") == "cat_id"
select el;
,这意味着如果您阅读多行,就会出现问题。答案 1 :(得分:0)
我不明白为什么在没有看到你正在做的事情的情况下这不起作用:
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("=")) {
if (line.contains("text1")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
}
}
out.flush();
out.close();
答案 2 :(得分:-1)
确保满足第二个if条件,即行字符串包含&#34; text2&#34;。