如何创建一个随机文件名然后递增它?

how do I create a random file name then increment it?

单击结帐按钮时需要创建一个包含随机发票编号的文本文件。需要在方法中执行此操作。我不确定如何在方法中创建和增加随机文件名。我为此创建了一个方法,但我不知道从这里去哪里。

    private class checkoutListener implements ActionListener{



    @Override
    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton) e.getSource();

        if(button == CheckoutBtn){



        }

在你的函数之外,像这样:

String name = "someName";
int counter = 1;

在你的函数中:

File f = new File(name+counter+".txt");
// Write...
counter++;

这会访问文件 someName1.txt、someName2.txt 等。然后使用 printwriters 或输出流在该文件上写入。

你的意思是这样的吗:

int randomInvoice = Math.round(Math.random() * 1000000);
File myfile1 = new File("file" + randomInvoice); // create file 1
myfile1.createNewFile();
...
randomInvoice++; // increase
File myfile2 = new File("file" + randomInvoice);
myfile2.createNewFile(); // create file 2

更新:尝试使用这样的东西:

private class checkoutListener implements ActionListener{
    private int randomInvoice = Math.round(Math.random() * 10000);

@Override
public void actionPerformed(ActionEvent e) {
    JButton button = (JButton) e.getSource();

    if(button == CheckoutBtn){
        randomInvoice++;
        File file = new File("invoice" + randomInvoice + ".txt");
        file.createNewFile();
        ... // working with file
    }