gpt4 book ai didi

java - 长类型输出文件

转载 作者:行者123 更新时间:2023-12-01 17:06:09 26 4
gpt4 key购买 nike

我尝试创建一个文件并用 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;
}
}

最佳答案

我假设您希望程序打印人类可读的 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 .

关于java - 长类型输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25453186/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com