长类型输出文件

时间:2014-08-22 18:12:44

标签: java file

我尝试创建一个文件,并用Java编写程序的输出。当我使用WriteLong时,该文件不包含长值。请解释我如何创建此文件。 我的程序是在50000010000000

之间打印素数
public class primenumber {

    public static void main(String[] args) {

        long start = 5000000;
        long end = 10000000;
        System.out.println("List of prime numbers between " + start + " and " + end);
        for (long i = start; i <= end; i++) {
            if (isPrime(i)) {
                System.out.println(i);
            }
        }
    }

    public static boolean isPrime(long i2) {
        if (i2 <= 1) {
            return false;
        }
        for (long i = 2; i < Math.sqrt(i2); i++) {
            if (i2 % i == 0) {
                return false;
            }
        }
        return true;
    }
}

2 个答案:

答案 0 :(得分:4)

我假设您希望程序打印人类可读的ASCII长值。您可以使用PrintWriter之类的内容,

PrintWriter pw = null;
try {
    pw = new PrintWriter(filePath);
    pw.println("List of prime numbers between " + start + " and " + end);
    for (long i = start; i <= end; i++) {
        if (isPrime(i)) {
            pw.println(i);
        }
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    pw.close();
}

或使用try-with-resources

try (PrintWriter pw = new PrintWriter(filePath)) {
    pw.println("List of prime numbers between " + start + " and " + end);
    for (long i = start; i <= end; i++) {
        if (isPrime(i)) {
            pw.println(i);
        }
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

如果您想创建二进制文件,可以使用DataOutputStream

答案 1 :(得分:1)

您需要使用PrintWriter,例如:

import java.io.*;

public class primenumber {

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

    long start = 5000000;
    long end = 10000000;
       System.out.println("List of prime numbers between " + start + " and " + end);
       PrintWriter pw = new PrintWriter(new FileOutputStream("primes.txt"));

       for (long i = start; i <= end; i++) {
           if (isPrime(i)) {
               pw.println(i);
           }
       }
       pw.close();
   }

   public static boolean isPrime(long i2) {
       if (i2 <= 1) {
           return false;
       }
       for (long i = 2; i < Math.sqrt(i2); i++) {
           if (i2 % i == 0) {
               return false;
           }
       }
       return true;
   }
}