java - 在 Java 中创建一个充满随机整数的文本文件

标签 java file text file-io random

愚蠢的问题,也许吧。但我尝试用 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等

最佳答案

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

不要使用它。

您使用一个 BufferedWriter 并且一个 BufferedWriter.newLine()

因此替换为:

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

关于java - 在 Java 中创建一个充满随机整数的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30284921/

相关文章:

java - 在 J2SE 应用程序中查看 Commons Logging 调试消息

ios - 如何在txt文件中编写iOS 7

java - 构建非常简单的极简 Java 插件容器

java - NoClassDefFoundError : com. sforce.soap.enterprise.Connector

Python 程序在读取文本文件时打印一个额外的空行

ios - 如何从 iOS 的 epub 格式中提取 txt

Java AES 加密 : Given final block not properly padded

css - 当白色 css 文本不透明度低于 1 时,会出现烦人的重叠

java - Castor - MappingException Java 类不可构造

java - Apache Camel 获取交换路径