1
我正試圖寫入一個文本文件,該文件將包含我以後打算處理的大塊文本。有很多我必須處理的變量組合,並且全部輸入變得太乏味。我試過兩次運行這段代碼,它所做的只是一遍又一遍地覆蓋第一行,給了我最後一個可能的變量組合。這是代碼。Java - 將文本追加到文件結尾
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();
}
*/
我需要知道的是如何給每個塊附加到文件行。另外,我遇到了一些奇怪的問題,即使我已經包含「\ n」來分隔變量列表,但它全部出現在一行上。底部的註釋代碼最初包含在「writer.println()」行之前。
可能重複? http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java –
@JohnDorian好吧,它似乎解決了寫入該文件的問題,但它贏了不打印到新的行。再次,文本都被集中在一起。 – user3308219
嘗試分別調用writer.println()爲每一行你想要的,不知道它是否會工作,但值得一試。像writer.println(精度); writer.println(條件); writer.println(specLevel);等等 –