gpt4 book ai didi

Java - 将文本附加到文件末尾

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:31 24 4
gpt4 key购买 nike

我正在尝试写入一个文本文件,该文件将只包含我计划稍后处理的大文本 block 。我必须处理许多变量的组合,将它们全部输入出来太乏味了。我尝试运行这段代码两次,它所做的只是一遍又一遍地覆盖第一行,给我最后可能的变量组合。这是代码。

import java.util.*;
import java.io.*;
public class FileWritingThing {
public static void main(String[]args) throws IOException{
String precision = null;
String criteria = null;
String specLevel = null;
String precondLevel = null;
PrintWriter writer = null;

for(int i = 0; i < 3; i++){
if(i == 0){
precision = "Precision = 4;";
}
if(i == 1){
precision = "Precision = 8;";
}
if(i == 2){
precision = "Precision = 12;";
}
for(int j = 0; j < 3; j++){
if(j == 0){
criteria = "Objective Function;";
}
if(j == 1){
criteria = "Domain;";
}
if(j == 2){
criteria = "Objective Function + Domain;";
}
for(int k = 0; k < 3; k++){
if(k == 0){
specLevel = "Speculation Level = 10000;";
}
if(k == 1){
specLevel = "Speculation Level = 100000;";
}
if(k == 2){
specLevel = "Speculation Level = 1000000;";
}
for(int l = 0; l < 3; l++){
if(l == 0){
precondLevel = "Precondition Level = 0;";
}
if(l == 1){
precondLevel = "Precondition Level = 25;";
}
if(l == 2){
precondLevel = "Precondition Level = 100;";
}
writer.println(precision + "\n" + criteria + "\n" + specLevel + "\n" + precondLevel + "\n");
}
}
}
}
writer.close();
}

}

/*try {
writer = new PrintWriter(new BufferedWriter(new FileWriter("permutations.txt", true)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/

我需要知道的是如何将每个 block 附加到文件行。此外,我遇到了一些奇怪的问题,即使我包含“\n”来分隔变量列表,它仍然显示在一行上。底部的注释代码最初包含在“writer.println()”行之前。

最佳答案

如果注释行位于 writer.println() 上方,那么它可能可以解释您遇到的奇怪行为。您应该在 for 循环之外创建 PrintWriter。像这样的事情

PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter("permutations.txt", true)));
// Most outer for loop goes here
for(int i=0......) {
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e) { e.printStackTrace(); }
finally {
if(writer!=null) {
try {
writer.flush();
writer.close();
} catch(Exception ignore) {}
}
}

关于Java - 将文本附加到文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com