M
M
MakarMS2020-10-25 04:14:56
Java
MakarMS, 2020-10-25 04:14:56

Why do variables in a method retain their value the next time they are called?

Hello! I've been struggling with this for 3 hours now. I am creating a sales telegram bot. I have a method. When calling, I pass it the path to the folder with the product and the label for the product. After the call, the method looks at all the files in this directory, then takes the first file, then sends it to the person and deletes the sent file.

The main problem is that when the method is called a second time, the variables retain their value from the last time, and are not updated. Those. I took files[0] (the first file in the directory), sent it, deleted it. I call it a second time, and it sends back files[0] to me, although it should have given out the second file before deletion. How to make the method re-scan the folder for files, and put them into the array in a new way?

public void sendTov(String patch, String caption){

            ClassLoader classLoaderr = getClass ().getClassLoader ();
           
         File file = new File ( Objects.requireNonNull ( classLoaderr.getResource ( patch ) ).getFile () );

           String[] files = file.list ();
            String path = patch + files[0];
            try {
                sendDocument ( chat_id, caption, path );
                String del = "src/main/resources/" + patch + files[0];
                file = new File ( del );
                if (file.delete ()) {
                    System.out.println ( "succses" );
                } else System.out.println ( "error" );


            } catch (TelegramApiException e) {
                e.printStackTrace ();
            }
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2020-10-25
@MakarMS

There are several problems here:
1. It is better to move all work with files into a separate service. A method that looks for a file, and sends it, and also deletes it later, and somehow knows how to handle exceptions, clearly does not correspond to the Single Responsibility principle. "String patch, String caption" should also be wrapped in some object of the "Product" type.
2. If your application works with files, it is better to have these files in some separate place, and not in the resources folder. It is better to specify the path to the file storage in properties.
3. Use the java.nio package. Outside 2020.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question