使用类方法java将文本输出到文件



我有一个valet类方法,它应该将小时工资写入一个文件:

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()时,创建了文件"工资信息",但没有向其写入任何内容。我做错了什么?

首先使用try-catch处理Exception,然后在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();
    }

我认为这是另一种解决你的问题的方法,但是使用另一个类

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+"rn");
        out.close();
    }
}

你可能不应该声明一个匿名的FileOutputStream,你可能应该关闭你的PrintWriter

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

执行如下操作(如果是java7或以上版本):

 public void hourlyOverall()
    {
        try (PrintWriter out=new PrintWriter("wage info")){
           //new FileOutputStream("wage info",true);
           hourlyOverall=tips/hours+hourlyWage;
           out.println(hourlyOverall);
        }catch (FileNotFoundException e) {
           e.printStackTrace();
        }
    }
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

最新更新