我尝试创建一个文件,并用Java编写程序的输出。当我使用WriteLong
时,该文件不包含长值。请解释我如何创建此文件。
我的程序是在500000
和10000000
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;
}
}
答案 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 (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;
}
}