[英]Java - Append text to end of file
我正在嘗試寫入一個文本文件,該文件將只包含我計划稍后處理的大塊文本。 我必須處理許多變量組合,而將它們全部鍵入很繁瑣。 我試過兩次運行此代碼,它所做的就是一遍又一遍地覆蓋第一行,這給了我變量的最后組合。 這是代碼。
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()”行之前。
如果注釋行在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) {}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.