用txt写java代码_java-每次我使用格式化程序在txt中写入内容...

import java.io.FileNotFoundException;

import java.lang.SecurityException;

import java.util.Formatter;

import java.util.FormatterClosedException;

import java.util.NoSuchElementException;

import javax.swing.JOptionPane;

public class CreateTextFile {

private Formatter output; //object used to output text to file

private Order order;

//enable user to open file

public void openFile()

{

try

{

output=new Formatter("src\Orders.txt");//pen the file

}//end try

catch(SecurityException securityException)

{

JOptionPane.showMessageDialog(null,"You do not have the write access to this file.","Error", JOptionPane.ERROR_MESSAGE);

System.exit(1);//terminate the program

}//end catch

catch(FileNotFoundException filenotfoundexception)

{

JOptionPane.showMessageDialog(null,"Error opening or creating file.","Error", JOptionPane.ERROR_MESSAGE);

System.exit(1);//terminate the program

}//end catch

}//end method openFile

//add records to file

public void addOrderstoSalesmen(String Description,String Date, double poso,int salesman,Employee currentEmployee)

{

try //output values to file

{

//retrieve data to be ouput

order=new Order(Description,Date,poso,salesman);

Salesman employee=(Salesman) currentEmployee;

employee.addOrder(order);

employee.setGrossSales(salesman);

output.format("%s,%s,%.0f

",order.getDescription(),order.getDate(),order.getSales());

}//end try

catch(FormatterClosedException formatterclosedexception)

{

JOptionPane.showMessageDialog(null,"Error writing to file.","Error", JOptionPane.ERROR_MESSAGE);

return;

}//end catch

catch(NoSuchElementException elementexception)

{

JOptionPane.showMessageDialog(null,"Invalid input.Please try again.","Error", JOptionPane.ERROR_MESSAGE);

}//end catch

}//end method addRecords

public void CloseFile()

{

if(output!=null)

output.close();

}//end method closeFile

}//end class CreateTextFile

最佳答案

您可能正在打开,写入,关闭文件,然后重复.每次打开文件进行写入时,其内容都会被清除干净.您可以通过以下任一方法解决此问题:

>打开,写入,写入,…,写入并仅在完成所有写入后关闭文件.

>以追加模式打开文件,因此不会删除旧内容.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值