Sthatyc Soul.
Sthatyc Soul.

Reputation: 136

Add a dynamic name to file

I made a button that creates txt files, here all works fine.

But the problem is when I create the first: TXT file, I dont know what I need or what I need to do, to continue creating TXT files, dynamically.

Here is my code:

int c;
c = 0;
c++;
String Name = "TXT" + c +".txt";
File TXT = new File(Name);
TXT.createNewFile();

This create a: TXT1.txt But not creating a TXT2.txt, TXT3.txt, etcetera.

I want increment the number dynamically. Thank you for read.

Upvotes: 1

Views: 427

Answers (3)

Igoranze
Igoranze

Reputation: 1486

1) Inside vs Outside:

If you declare your object inside a method, it will be visible only in this method. Basically, if you put brackets around it, it's only visible/accessible from within these brackets.

If you declare your object outside the method (inside the class), it depends on the access modifier. By default, it's visible/accessible from within that class and the whole package.

2) Static

Static means, that this Object/Variable belongs to the class itself, and not to its objects

source

To simulate the button click, I made this small code:

package main.application;

import java.io.File;
import java.io.IOException;

public class Main {

    private static int incrementFileName = 1;
    private static final String PATH = "C:\\Users\\user\\Desktop\\";

    public static void main(String[] args) throws IOException {

        //Each time the button is pressed.
        for (int c = 0; c < 5; c++)
        {
            incrementFileName++;
            buttonClicked();
        }
    }

    private static void buttonClicked() throws IOException
    {
        String Name = "TXT" + incrementFileName +".txt";
        File TXT = new File(PATH + Name);
        TXT.createNewFile();
    }
}

As you can see, you need to declare the incrementFileName (your c) outside the method which is used to create a new File, and increment it each time a button is pressed.

Upvotes: 0

J. Hegg
J. Hegg

Reputation: 2073

Wrap it in a for loop and exclude the counter like this:

for(int i = 1; i < yourMaximumRun; ++i)
{

    String Name = "TXT" + i +".txt";
    File TXT = new File(Name);
    try
    {
        TXT.createNewFile();
    }
}

Upvotes: 2

madstalin
madstalin

Reputation: 21

If this is the code in your method, c always gets initiated with 0 and incremented to 1.

If you hit the button again, c will again be initiated with 0 and incremented. You need to persist your c somewhere outside of the method instead of re-initializing it everytime.

Upvotes: 1

Related Questions