[英]using PrintWriter to write strings to log file
我有一個Java應用程序,需要將大量數據寫入文本文件中的單獨行中。 我寫了下面的代碼來做到這一點,但是由於某種原因,它沒有在文本文件中寫任何東西。 它確實創建了文本文件,但是在程序運行完之后,文本文件仍然為空。 誰能告訴我如何修復下面的代碼,以使它實際上能按要求的行數填充輸出文件?
public class MyMainClass{
PrintWriter output;
MyMainClass(){
try {output = new PrintWriter("somefile.txt");}
catch (FileNotFoundException e1) {e1.printStackTrace();}
anotherMethod();
}
void anotherMethod(){
output.println("print some variables");
MyOtherClass other = new MyOtherClass();
other.someMethod(this);
}
}
public class MyOtherClass(){
void someMethod(MyMainClass mmc){
mmc.output.println("print some other variables")
}
}
使用其他構造函數:
output = new PrintWriter(new FileWriter("somefile.txt"), true);
根據JavaDoc :
public PrintWriter(Writer out, boolean autoFlush)
創建一個新的PrintWriter。
參數:
out-字符輸出流
autoFlush-一個布爾值; 如果為true,則println,printf或format方法將刷新輸出緩沖區
使用其他構造函數new PrintWriter(new PrintWriter("fileName"), true)
進行自動刷新數據,或在完成編寫后使用flush()
和close()
您如何做到這一點對我來說似乎很奇怪。 為什么不編寫一種將字符串輸入然后將其寫入文件的方法? 這樣的事情應該可以正常工作
public static void writeToLog(String inString)
{
File f = new File("yourFile.txt");
boolean existsFlag = f.exists();
if(!existsFlag)
{
try {
f.createNewFile();
} catch (IOException e) {
System.out.println("could not create new log file");
e.printStackTrace();
}
}
FileWriter fstream;
try {
fstream = new FileWriter(f, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(inString+"\n");
out.newLine();
out.close();
} catch (IOException e) {
System.out.println("could not write to the file");
e.printStackTrace();
}
return;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.