编写程序以读取数字列表,确定它们是否为素数,然后将其写入文件。早些时候发布了这个问题。修正了我的逻辑以确定数字是否为素数。现在我看不到要写入名为“PrimeNumbers.txt”的文本文件
有一次我能够写一行,但现在没有任何内容写入文本文件。请指教。
import java.io.*;
import java.util.Scanner;
public class AssignFive_FileRead {
public static void main(String[] args) throws IOException {
int number;
int count = 0;
int calc = 0;
int i = 2;
File myFile = new File("assignment5Numbers.txt");
File myTargetFile = new File("PrimeNumbers.txt");
Scanner inputFile = new Scanner(myFile);
System.out.println("** Checking for required files **");
// Check to see if file's exists
if (!myTargetFile.exists()) {
System.out.println("Error: Unable to create target file!");
System.exit(0);
} else {
System.out.println("Target file has been created!");
}
if (!myFile.exists()) {
System.out.println("Error: file cannot be found");
System.exit(0);
} else {
System.out.println("Source file has been found, starting operation...");
System.out.println();
}
// Reading numbers from text file
while (inputFile.hasNext()) {
number = inputFile.nextInt();
while (i <= number / 2) {
if (number % i == 0) {
calc = 1;
}
i++;
} // End second while loop
if (calc != 1) {
count++;
for (int x = 0; x <= count; x++) {
PrintWriter outputFile = new PrintWriter("PrimeNumbers.txt");
outputFile.print(number + "\t");
outputFile.println("is prime");
}
}
// resetting variables for next check
calc = 0;
i = 2;
} // End first while loop
// System.out.println("Source file has a total of " + count + " numbers");
System.out.println("Data has been written to files.. Operation successful!");
} // End main
} // End public class
答案 0 :(得分:1)
在你的PrintWriter outputFile
循环之外对你的while
进行decalre,你将重用PrintWriter
并且你想要将其当前内容/位置保留在文件中,所以它不应该是每次解析另一个数字时重新声明。同样重命名,名称不代表它的作用,称之为outputWriter
。
您需要.close()
输入和输出流,这可以确保已刷新缓冲区并从Java应用程序中释放资源。在System.out.println("Data has been written to files.. Operation successful!");
放置outputFile.close();
和inputFile.close();