2014-07-12 86 views
0

我應該寫一個小時的薪酬文件的valet類方法的文件:輸出文本與類方法的Java

public void hourlyOverall() throws FileNotFoundException 
{ 
    PrintWriter out = new PrintWriter("wage info"); 
    new FileOutputStream("wage info", true); 
    hourlyOverall = tips/hours + hourlyWage; 
    out.println(hourlyOverall); 
} 

然而,當我在main方法運行valet.hourlyOverall(),文件「工資信息「被創建,但沒有寫入它。我究竟做錯了什麼?

+3

關閉'OutputStream' – Reimeus

回答

0

你可能不應該聲明一個匿名FileOutputStream,你或許應該關閉PrintWriter

PrintWriter out=new PrintWriter("wage info"); 
// new FileOutputStream("wage info",true); 
hourlyOverall=tips/hours+hourlyWage; 
out.println(hourlyOverall); 
out.close();        // <-- like that 
1

首先使用try-catchException處理,然後在finally塊關閉OutputStream

out.flush();

類似這樣的東西

try { 
     PrintWriter out = new PrintWriter("wage info"); 
     hourlyOverall=tips/hours+hourlyWage; 
     out.println(hourlyOverall); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    finally { 
     out.flush(); 
    } 
1

我認爲這是另一種方式來解決問題,但使用另一個類

public class valet { 
    public static void main(String []args)throws IOException 
    { 
     try 
     { 
      hourlyOverall() 
     } 
     catch(IOException ex) 
     { 
      System.out.println(ex+"\n"); 
     } 
    } 

    public void hourlyOverall() throws IOException 
    { 
     FileWriter out = new FileWriter("wage info"); 
     hourlyOverall=tips/hours+hourlyWage; 
     out.write(hourlyOverall+"\r\n"); 
     out.close(); 
    } 
}