2012-03-29 60 views
10

我創建的java項目將被測試1800個案例,並且每個案例的輸出必須與黃金(期望)輸出匹配。我爲此創建了一個perl腳本並在cygwin上運行它。向文件寫入例外

有幾種情況會引發異常,但它們被錯誤地認爲是正確的。我想在java代碼中添加一個try catch塊,這樣如果拋出任何異常,它將被捕獲並且堆棧跟蹤將被打印在文件exception.txt上。

Pseudo Java code: 
main() 
{ 
    try 
    { 
     ... //complete code of main() 
    } 
    catch (Exception e) 
    { 
     FileWriter fstream=new FileWriter("exception.txt"); 
     BufferedWriter out=new BufferedWriter(fstream); 
     out.write(e.toString()); 
     out.close(); 
    } 
} 

但是這覆蓋了以前的文件內容,最後文件包含最後拋出的異常。我如何編寫catch塊以便打印stackTrace並且文件的內容是完整的並且不會每次都被覆蓋。

+0

使用其他CONSTRU FileWriter'FileWriter(「exception.txt」,true)的ctor;' – Kayser 2012-03-29 10:40:13

+0

您可以使用Printstream進行堆棧跟蹤。我解釋瞭如何在答案。 – Kayser 2012-03-29 10:58:52

回答

20

使用此構造函數來代替:

new FileWriter ("exception.txt", true); 

它被描述here

編輯:按照下面喬恩的評論:

如果你想打印整個堆棧跟蹤,使用printStackTrace

fw = new FileWriter ("exception.txt", true); 
pw = new PrintWriter (fw); 
e.printStackTrace (pw); 

此外,使用後,適當close電話。

+0

但是我怎樣才能寫stackTrace? – 2012-03-29 10:43:05

+0

這是一個單獨的問題。你可以得到一個StackTraceElement []從的getStackTrace(),然後爲每個StackTraceElement的使用上的StackTraceElement的方法來獲取文件名,行號等打印每個組信息一行。 – Jon 2012-03-29 10:50:47

+0

你也可以使用這個http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable。html#printStackTrace(java.io.PrintWriter)並提供一個包裝現有FileWriter的PrintWriter。 – Jon 2012-03-29 10:53:31

5

使用

FileWriter fstream=new FileWriter("exception.txt", true); 

創建追加文件作家。

4

這裏是一個程序,證明什麼,我想你需要:

 

import java.io.BufferedWriter; 
import java.io.FileWriter; 
import java.io.PrintWriter; 

public class StrackTraceAppender { 

    public static void main(String[] args) { 
     try { 
     thrower("Oh noes!"); 
     } catch (Exception e) { 
     appendToFile(e); 
     } 

     try { 
     thrower("I died!"); 
     } catch (Exception e) { 
     appendToFile(e); 
     } 
    } 

    public static void thrower(String message) throws Exception { 
     throw new RuntimeException(message); 
    } 

    public static void appendToFile(Exception e) { 
     try { 
     FileWriter fstream = new FileWriter("exception.txt", true); 
     BufferedWriter out = new BufferedWriter(fstream); 
     PrintWriter pWriter = new PrintWriter(out, true); 
     e.printStackTrace(pWriter); 
     } 
     catch (Exception ie) { 
     throw new RuntimeException("Could not write Exception to file", ie); 
     } 
    } 
} 
 

它使用上的Throwable的printStackTrace(PrintWriter)方法打印整個堆棧跟蹤到一個文件名爲「exception.txt」結束,然後有一個main()方法,演示兩個示例異常的用法。如果你在你的IDE中運行它,你會發現你得到了一個寫有兩個棧跟蹤的文件(適用於我)。

+1

+1記住OP有*還*詢問如何打印堆棧跟蹤。 – ArjunShankar 2012-03-29 12:13:39

9

您可以使用:

FileOutputStream fos = new FileOutputStream(new File("exception.txt"), true); 
PrintStream ps = new PrintStream(fos); 
e.printstacktrace(ps); 
0

試試這個:

import java.io.File; 
import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Paths; 
import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.logging.*; 

public class ErrorLogger 
{ 
    private Logger logger; 

    public ErrorLogger() 
    { 
     logger = Logger.getAnonymousLogger(); 

     configure(); 
    } 

    private void configure() 
    { 
     try 
     { 
      String logsFolder = "logs"; 
      Files.createDirectories(Paths.get(logsFolder)); 
      FileHandler fileHandler = new FileHandler(logsFolder + File.separator + getCurrentTimeString() + ".log"); 
      logger.addHandler(fileHandler); 
      SimpleFormatter formatter = new SimpleFormatter(); 
      fileHandler.setFormatter(formatter); 
     } catch (IOException exception) 
     { 
      exception.printStackTrace(); 
     } 

     addCloseHandlersShutdownHook(); 
    } 

    private void addCloseHandlersShutdownHook() 
    { 
     Runtime.getRuntime().addShutdownHook(new Thread(() -> 
     { 
      // Close all handlers to get rid of empty .LCK files 
      for (Handler handler : logger.getHandlers()) 
      { 
       handler.close(); 
      } 
     })); 
    } 

    private String getCurrentTimeString() 
    { 
     DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); 
     return dateFormat.format(new Date()); 
    } 

    public void log(Exception exception) 
    { 
     logger.log(Level.SEVERE, "", exception); 
    } 
} 

用法:

ErrorLogger errorLogger = new ErrorLogger(); 

try 
{ 
    throw new Exception("I died!"); 
} catch (Exception exception) 
{ 
    errorLogger.log(exception); 
} 
2

試試這個:

PrintStream printStream = new PrintStream(new File("exception.txt")); 
try { 
    //error proven code 
} catch (Exception exception) { 
    exception.printStackTrace(printStream); 
}