【问题标题】:how do I create a random file name then increment it?如何创建一个随机文件名然后增加它?
【发布时间】:2016-03-01 05:55:49
【问题描述】:

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

    private class checkoutListener implements ActionListener{



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

        if(button == CheckoutBtn){



        }

【问题讨论】:

  • 这是什么编程语言?这似乎没有正确标记。我认为您的意思是将您的问题标记为java,这与javascript 非常不同。
  • 嗨,smh,DelightedD0D 已将标签 javascript 替换为 java,但您已将其改回 javascript。你能解释一下为什么你应用了这个标签,而你的代码示例是用java写的吗?
  • 对不起,我想我在标记项目方面还是有点困惑。

标签: java file methods text-files


【解决方案1】:

你的意思是这样的:

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
    }

【讨论】:

【解决方案2】:

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

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

在你的函数内部:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 2015-11-12
    • 2019-06-23
    • 1970-01-01
    • 2021-12-11
    • 2012-03-24
    • 2021-03-24
    相关资源
    最近更新 更多