Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java FileWriter skip files

I have a package with files : "100.txt" ,"1000.txt", "10000.txt","100000.txt", "1000000.txt".
But when i launch my program, it skips 100 and 1000 txt files. Can you tell me why?

public void generateData(Path path) throws IOException {
        for (int i = 1; i <= 5; i++){
            for (int j = 100; j <= 1000000; j*=10){
                FileWriter fileWriter = new FileWriter(path.resolve(Integer.toString(i)).resolve(j + ".txt").toFile());
                Random random = new Random();
                for (int k = 0; k < j; k++){
                    int num = random.nextInt(10);
                    fileWriter.write(num);
                    fileWriter.write("\n");
                }
            }
        }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I ran your code and everything seemed to run pretty well.

All files were printed:

  • 100.txt
  • 1000.txt
  • 10000.txt
  • 100000.txt
  • 1000000.txt

One thing I noticed is that you don’t close your FileWriter after you’re done with it. Perhaps that is the problem.

Here is the full code I ran. I did remove the writing of the files into the numbered directories since those directories didn’t exist on my machine.

package forloop;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;

public class GenerateData {

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

        Path path = Paths.get("");

        generateData(path);
    }

    public static void generateData(Path path) throws IOException {
        for (int i = 1; i <= 5; i++){
            for (int j = 100; j <= 1000000; j*=10){
                FileWriter fileWriter = new FileWriter(path.resolve(j + ".txt").toFile());
                Random random = new Random();
                for (int k = 0; k < j; k++){
                    int num = random.nextInt(10);
                    fileWriter.write(num);
                    fileWriter.write("\n");
                }
                fileWriter.close();
            }
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading