创建一个用 Java 中的随机整数填充的文本文件

Creating a text file filled with random integers in Java

愚蠢的问题,也许吧。但我尝试用 512 个整数填充一个空文本文件,每个整数都在每一行。我能够随机化并将它们写入文件,但它们会产生一大堆我想要的数字。谁能帮我更正我的代码?

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class Randomizer {

      public static void main() {
        // The target file
        File out = new File("random.txt");
        FileWriter fw = null;
        int n = 512;
        // Try block: Most stream operations may throw IO exception
        try {
            // Create file writer object
            fw = new FileWriter(out);
            // Wrap the writer with buffered streams
            BufferedWriter writer = new BufferedWriter(fw);
            int line;
            Random random = new Random();
            while (n > 0) {
                // Randomize an integer and write it to the output file
                line = random.nextInt(1000);
                writer.write(line + "\n");
                n--;
            }
            // Close the stream
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(0);
        }
    }
}

random.txt 的内容在 运行 的末尾: 9463765593113665333437829621346187993554694651813319223268147794541131427390等

您似乎正在使用 Windows - Unix/Windows/Classic Mac 上的行结尾不同。

尝试 \r\n 基于 Windows 的系统,或尝试在写字板而不是记事本中打开 .txt 文件 - \n 通常用于 Unix 系统,记事本应用程序包含在 Windows 众所周知处理不好。

            writer.write(line + "\n");

不要使用那个。

您使用 BufferedWriter 并且 BufferedWriter.newLine()

因此替换为:

writer.write(line);
writer.newLine();

检查 javadoc 中的这一行 BufferedWriter:

A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.