简体   繁体   English

当尝试打印 2 到 1000 之间的质数时,PrintWriter 在文本文件中写入一些其他字符

[英]PrintWriter writes some other characters in text file when trying to print prime numbers between 2 to 1000

I'm trying to print prime numbers between 2 and 1000 but it is writing some other characters in text file我正在尝试打印 2 到 1000 之间的质数,但它正在文本文件中写入一些其他字符

Here is the contents of my TreeSet:这是我的 TreeSet 的内容:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619,
631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743,
751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]

Here is snippets of my code retrieving and printing the above prime numbers into the text file "PrimeNumbersList.txt":以下是我检索上述质数并将其打印到文本文件“PrimeNumbersList.txt”中的代码片段:

        pw = new PrintWriter("PrimeNumbersList.txt");
        int count = 0;
        for(Long l: treeSet){
            if(count==0){
                pw.print(""+l);
                pw.flush();
                count++;
                continue;
            }
            pw.print("\n"+l);
            pw.flush();
        }

Expected output:预期输出:

2
3
5
.
.
.
997

The output I got:我得到的输出:

ਲਲ਼ਵ਷ㄱㄊਲ਼㜱ㄊਹ㌲㈊ਹㄳ㌊਷ㄴ㐊ਲ਼㜴㔊ਲ਼㤵㘊਱㜶㜊਱㌷㜊ਹ㌸㠊ਹ㜹ㄊ㄰ㄊ㌰ㄊ㜰ㄊ㤰ㄊ㌱ㄊ㜲ㄊㄳㄊ㜳ㄊ㤳ㄊ㤴ㄊㄵㄊ
㜵ㄊ㌶ㄊ㜶ㄊ㌷ㄊ㤷ㄊㄸㄊㄹㄊ㌹ㄊ㜹ㄊ㤹㈊ㄱ㈊㌲㈊㜲㈊㤲㈊㌳㈊㤳㈊ㄴ㈊ㄵ㈊㜵㈊㌶㈊㤶㈊ㄷ㈊㜷㈊ㄸ㈊㌸㈊㌹㌊㜰㌊
ㄱ㌊㌱㌊㜱㌊ㄳ㌊㜳㌊㜴㌊㤴㌊㌵㌊㤵㌊㜶㌊㌷㌊㤷㌊㌸㌊㤸㌊㜹㐊㄰㐊㤰㐊㤱㐊ㄲ㐊ㄳ㐊㌳㐊㤳㐊㌴㐊㤴㐊㜵㐊ㄶ㐊㌶㐊
㜶㐊㤷㐊㜸㐊ㄹ㐊㤹㔊㌰㔊㤰㔊ㄲ㔊㌲㔊ㄴ㔊㜴㔊㜵㔊㌶㔊㤶㔊ㄷ㔊㜷㔊㜸㔊㌹㔊㤹㘊㄰㘊㜰㘊㌱㘊㜱㘊㤱㘊ㄳ㘊ㄴ㘊㌴㘊
㜴㘊㌵㘊㤵㘊ㄶ㘊㌷㘊㜷㘊㌸㘊ㄹ㜊㄰㜊㤰㜊㤱㜊㜲㜊㌳㜊㤳㜊㌴㜊ㄵ㜊㜵㜊ㄶ㜊㤶㜊㌷㜊㜸㜊㜹㠊㤰㠊ㄱ㠊ㄲ㠊㌲㠊㜲㠊
㤲㠊㤳㠊㌵㠊㜵㠊㤵㠊㌶㠊㜷㠊ㄸ㠊㌸㠊㜸㤊㜰㤊ㄱ㤊㤱㤊㤲㤊㜳㤊ㄴ㤊㜴㤊㌵㤊㜶㤊ㄷ㤊㜷㤊㌸㤊ㄹ㤊㜹

Try it like this.像这样试试。

  • specify a character set.指定字符集。 Here I chose the default.这里我选择了默认。
  • use try with resources to both catch an exception and close the file. try with resources使用try with resources来捕获异常并关闭文件。
  • use println to print a line terminator after each value.使用println在每个值后打印行终止符。
  • the auto closing of the file will flush the output buffer.文件的自动关闭将刷新输出缓冲区。
try (PrintWriter pw = new PrintWriter("f:/PrimeNumbersList.txt",
          Charset.defaultCharset())) {
         
         for(long l: longs){
             pw.println(l);
         }
} catch (IOException ioe){
    ioe.printStackTrace();
}

The above printed the values, one per line, in the target file.以上在目标文件中打印了值,每行一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM