如何从Java中的循环写入同一行

时间:2019-04-03 19:34:12

标签: java

我编写了以下代码,在文本文件中写了一行,并使用循环增加了内容。问题是我使用的方法是将每个增量写在新行上,而不是追加。

for (int d = 10; d >= 1; d--) {        
    Path path = Paths.get("ScalModel.txt");
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

    int position = 75;
    String extraLine = "MainAttack -OR-> {AttackNode" + d + "}";

    lines.add(position, extraLine);
    Files.write(path, lines, StandardCharsets.UTF_8); 
} 

我想要得到的输出是:

MainAttack -OR-> {AttackNode1, AttackNode2, AttackNode3, AttackNode4, AttackNode5, AttackNode6, AttackNode7, AttackNode8, AttackNode9, AttackNode10}

我得到的是:

MainAttack -OR-> {AttackNode1}
MainAttack -OR-> {AttackNode2}
MainAttack -OR-> {AttackNode3}
MainAttack -OR-> {AttackNode4}
MainAttack -OR-> {AttackNode5}
MainAttack -OR-> {AttackNode6}
MainAttack -OR-> {AttackNode7}
MainAttack -OR-> {AttackNode8}
MainAttack -OR-> {AttackNode9}
MainAttack -OR-> {AttackNode10}

如何修改代码以获得预期的结果?

3 个答案:

答案 0 :(得分:1)

循环内有很多指令,必须放在循环外。这就像我要做的一样:

Path path = Paths.get("ScalModel.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);    

int position = 75;
String extraLine = "MainAttack -OR-> {";

for (int d = 10; d >= 1; d--) {        
    extraLine += "AttackNode"+d;
    if(d==1) extraLine += "}";
    else extraLine += ",";
}

lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8); 

如果您以自己的方式进行操作,则在获得答案之前,您正在读写文件10次。

答案 1 :(得分:0)

尝试使用字符串构建来构建字符串,然后一次性保存

StringBuilder sb = new StringBuilder();
sb.append("MainAttack -OR-> {");
int position = 75;
for (int d = 1; d <= 10; d++) {
    if(d!=10)
        sb.append("AttackNode" + d + ", ");
    else
        sb.append("AttackNode" + d + " ");
}
sb.append("}");
Path path = Paths.get("ScalModel.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.add(position, sb);
Files.write(path, lines, StandardCharsets.UTF_8); 

随意编辑

答案 2 :(得分:0)

以下是您的原因的简单示例:

public static void main(String[] args) throws IOException {

        Path path = Paths.get("ScalModel.txt");
        try {
            String initialText = "MainAttack -OR->";
            for (int d = 1; d <= 10; d++) {
                initialText += " {AttackNode" + d + "}";
            }
            byte[] bytes = initialText.getBytes();
            Files.write(path, bytes);
        } catch (IOException ioE) {
            System.err.println("JVM reported an error! Take a look: " + ioE);
        }

    }