我无法弄清楚为什么以下简单程序没有(创建)然后写入文件?你能发现问题所在吗?
public class RandomSeq
{
public static void main( String[] args)
{
// command-line argument
int N = Integer.parseInt( args[0] );
// generate and print N numbers between 0 and 1
for ( int i = 0 ; i < N; i++ )
{
// System.out.println( Math.random() );
StdOut.println( Math.random() );
}
}
}
在Interactions提示符下键入以下内容时:
java RandomSeq 5
0.9959531649155268
0.5010055704125982
0.4444779637605908
0.4205901267129799
0.09968268057133955
我显然得到了正确的输出,但是当我使用滚边时,它不会做(我认为)它应该做的事情:
> java RandomSeq 5 > f1.txt
答案 0 :(得分:3)
写入文件的“普通”Java方法是使用Writer
类。我在下面举了一个小例子。或者,您可以更改您写入的PrintStream
,然后将输出发送到文件而不是控制台(基本上与下面相同)
PrintWriter out;
File myfile = new File(folder,"output.txt");
myfile.createNewFile();
fos = new FileOutputStream(myfile);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fos, "UTF-8")));
out.println("some text to go in the output file");
修改强>
在我的机器上,代码使用System.out.println()
正常工作。我只能想象写权限可能有问题,否则可能StdOut
对象有一些错误......
~/scratch $ java RandomSeq 5 > out.txt
~/scratch $ cat out.txt
0.5674462012296635
0.05189786036638799
0.1290205079541452
0.22015961731674394
0.6503198654182695
~/scratch $
答案 1 :(得分:0)
我尝试过使用system.out,它对我来说非常适合。您的特定文件夹或目录可能存在读/写权限,因此您可能无法创建f1.txt。如果没有适当的权限,请尝试更改文件夹权限或用户权限。另外,请确保您正在程序创建的同一位置找到该文件。