在Java中创建一个填充随机整数的文本文件 [英] Creating a text file filled with random integers in Java

查看:193
本文介绍了在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(){
//目标文件
File out = new File(random.txt );
FileWriter fw = null;
int n = 512;
//尝试阻止:大多数流操作可能会抛出IO异常
尝试{
//创建文件编写器对象
fw = new FileWriter(out);
//使用缓冲流封装作者
BufferedWriter writer = new BufferedWriter(fw);
int line;
Random random = new Random();
while(n> 0){
//随机化整数并将其写入输出文件
line = random.nextInt(1000);
writer.write(line +\\\
);
n--;
}
//关闭流
writer.close();
} catch(IOException e){
e.printStackTrace();
System.exit(0);





内容random.txt at运行结束:
9463765593113665333437829621346187993554694651813319223268147794541131427390等。

解决方案

看来你使用的是Windows - 行结尾是不同的在Unix / Windows / Classic Mac上。



对于基于Windows的系统,请尝试\ r \\\
,或尝试在写字板而不是记事本中打开.txt文件 - \ n通常在Unix系统上使用,而Windows附带的Notepad应用程序已知不能很好地处理它们。


Stupid question, maybe. But I try to fill an empty text file with 512 integers, each on every new line. I was able to randomize and write them into the file, but they create a huge pile of numbers of what I have wished. Can anyone help me correct my code?

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);
        }
    }
}

Content of random.txt at the end of the run: 9463765593113665333437829621346187993554694651813319223268147794541131427390 etc.

解决方案

It seems that you are using Windows - line endings are different on Unix/Windows/Classic Mac.

Try \r\n for Windows-based systems, or try to open the .txt file in Wordpad instead of Notepad - \n is commonly used on Unix systems and the Notepad application included with Windows is known not to handle them well.

这篇关于在Java中创建一个填充随机整数的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆