在Java中创建一个填充随机整数的文本文件 [英] Creating a text file filled with random integers in Java
问题描述
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屋!