愚蠢的问题,也许吧。但我尝试用每个新行填充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等。
答案 0 :(得分:1)
writer.write(line + "\n");
不要使用它。
您使用BufferedWriter
而BufferedWriter
使用.newLine()
。
因此替换为:
writer.write(line);
writer.newLine();
答案 1 :(得分:0)
您似乎在使用Windows - 在Unix / Windows / Classic Mac上,行结尾不同。
尝试\ r \ n用于基于Windows的系统,或者尝试在Wordpad中打开.txt文件而不是记事本 - \ n n通常在Unix系统上使用,并且Windows中包含的记事本应用程序已知不能很好地处理它们
答案 2 :(得分:0)
从BufferedWriter
newLine()
查看此行:
提供了
'\n'
方法,该方法使用平台自己的行分隔符概念,由系统属性line.separator定义。并非所有平台都使用换行符(val parser = new scopt.OptionParser[Config]("scopt") { head("scopt", "3.x") opt[Int]('f', "foo") action { (x, c) => c.copy(foo = x) } text("foo is an integer property") opt[File]('o', "out") required() valueName("<file>") action { (x, c) => c.copy(out = x) } text("out is a required file property") opt[(String, Int)]("max") action { case ((k, v), c) => c.copy(libName = k, maxCount = v) } validate { x => if (x._2 > 0) success else failure("Value <max> must be >0") } keyValueName("<libname>", "<max>") text("maximum count for <libname>") opt[Seq[File]]('j', "jars") valueName("<jar1>,<jar2>...") action { (x,c) => c.copy(jars = x) } text("jars to include") opt[Map[String,String]]("kwargs") valueName("k1=v1,k2=v2...") action { (x, c) => c.copy(kwargs = x) } text("other arguments") opt[Unit]("verbose") action { (_, c) => c.copy(verbose = true) } text("verbose is a flag") opt[Unit]("debug") hidden() action { (_, c) => c.copy(debug = true) } text("this option is hidden in the usage text") note("some notes.\n") help("help") text("prints this usage text") arg[File]("<file>...") unbounded() optional() action { (x, c) => c.copy(files = c.files :+ x) } text("optional unbounded args") cmd("update") action { (_, c) => c.copy(mode = "update") } text("update is a command.") children( opt[Unit]("not-keepalive") abbr("nk") action { (_, c) => c.copy(keepalive = false) } text("disable keepalive"), opt[Boolean]("xyz") action { (x, c) => c.copy(xyz = x) } text("xyz is a boolean property"), checkConfig { c => if (c.keepalive && c.xyz) failure("xyz cannot keep alive") else success } ) }
)来终止行。因此,调用此方法终止每个输出行是首选直接写入换行符。