0

I am working on a program that is going to calculate alla prime numbers between 2 and 10 000 and write this to a file.

People tell different ways on how to write to a file so I took one sugestion and tried it. At first i put my file creation in a loop with ended in the program recreating the file each time, then I took the file creation out of the loop and now I get errors.

Could someone tell me if this is the way to do it, if not, how should it be done, or how can i make this work?

To already have a file could also work and then just add/edit/overwrite it from my program.

public static void main(String[] arg){
    int prime = 2;

    File file = new File("out.txt");      // how should i do this part
    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);     

    while(prime < 10000){
        boolean isPrime = true;

        for( int i = 2; i <= sqrt(prime); i++){
            if( (prime%i) == 0 ){
                isPrime = false;
                break;
            }
        }
        if(isPrime){
            bw.write(prime + " ");     // and this
        }
        prime++;
    }
}
user2792927
  • 3
  • 1
  • 2

5 Answers5

2

The code looks fine, just be sure to close your streams when you're done.

If you don't want to make a new file each time, you can open an existing file in write mode

How do I create a file and write to it in Java?

Community
  • 1
  • 1
Chris
  • 552
  • 4
  • 12
0

You must write and then close the FileWriter and BufferedWriter at the end.

Put these lines at the last after the loop --

bw.close();
fw.close();

In addition using FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); would let you append to the existing file. Please, notice the 'true'.

SSaikia_JtheRocker
  • 4,933
  • 1
  • 20
  • 39
0

I would put bw.write(prime + " "); in a try/catch block to exit gracefully if something fails. You might also want to inclue a file.createNewFile() statement if the file does not file.exists().

Lastly, make sure you bw.close() the buffered writer.

Other than that, yep, everything looks up to par.

I would do a:

try {
  bw.write(stuff);
}
Catch (IOException e) {
  e.printStackTrace();
}
aristotll
  • 6,572
  • 5
  • 30
  • 47
philhan
  • 510
  • 1
  • 6
  • 18
  • I put the try/catch block in my if statement and the bw.close(); after my while loop but it still wont compile. It says: "unreported exception ioexception must be caught or declared to be thrown" over my file creation – user2792927 Sep 18 '13 at 19:55
0

My guess is that your errors are due to checked exceptions that some of your code can throw and that you are not catching or declaring main to throw. You are also potentially leaking resources. If you are using Java 7, I suggest the following (using a try-with-resources statement):

public static void main(String[] arg){
    File file = new File("out.txt");
    try (
        BufferedWriter bw = new BufferedWriter(new FileWriter(file))
    ) {
        for (int prime = 2; prime < 10000; ++prime) {
            boolean isPrime = true;
            final int limit = (int) sqrt(prime); // 
            for (int i = 2; i <= limit && isPrime; i++) {
                isPrime = prime % i != 0;
            }
            if (isPrime){
                bw.write(String.valueOf(prime));
                bw.newLine();
            }
        }
    } catch (IOException ex) {
        e.printStackTrace();
    }
}

Prior to Java 7, you should do something like this:

public static void main(String[] arg){
    File file = new File("out.txt");
    BufferedWriter bw = null;
    try {
        bw = new BufferedWriter(new FileWriter(file));

        for (int prime = 2; prime < 10000; ++prime) {
            boolean isPrime = true;
            int limit = (int) sqrt(prime);
            for( int i = 2; i <= limit && isPrime; i++) {
                isPrime = prime % i != 0;
            }
            if (isPrime) {
                bw.write(String.valueOf(prime));
                bw.newLine();
            }
        }
    } catch (IOException ex) {
        e.printStackTrace();
    } finally {
        if (bw != null) {
            try { bw.close(); }
            catch (IOException ignored) { }
        }
    }
}

As an aside, your approach to testing primality is extremely inefficient. You might want to take a look at using the Sieve of Eratosthenes.

Ted Hopp
  • 222,293
  • 47
  • 371
  • 489
  • Thank you! Now it works as it should! I am aware that this method is not the best but it is an easy way. But i will look into your suggestion and maybe do another program with that method! – user2792927 Sep 18 '13 at 20:13
0

Use a StringBuffer to cache all the prime numbers and after the for loop completes iterating over all the numbers, convert the StringBuffer to a String and write to your output file in one go.

Trey Jonn
  • 340
  • 3
  • 17