簡體   English   中英

打印到文件 - Java 初學者

[英]Printing to File - Java beginner

我不明白為什么下面的簡單程序不(創建)然后寫入文件? 你能找出問題所在嗎?

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

當我在交互提示符下鍵入以下內容時:

java 隨機序列 5

0.9959531649155268
0.5010055704125982
0.4444779637605908
0.4205901267129799
0.09968268057133955

我顯然得到了正確的 output,但是當我使用管道時,它沒有執行(我認為)它應該執行的操作:

> java RandomSeq 5 > f1.txt

寫入文件的“正常”Java 方式是使用Writer class。我在下面表示了一個小示例。 或者,您可以更改寫入的PrintStream ,然后將 output 發送到文件而不是控制台(與下面基本相同)

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 object 可能有一些錯誤......

~/scratch $ java RandomSeq 5 > out.txt
~/scratch $ cat out.txt 
0.5674462012296635
0.05189786036638799
0.1290205079541452
0.22015961731674394
0.6503198654182695
~/scratch $ 

我已經嘗試過 system.out,它非常適合我。 您的特定文件夾或目錄可能有讀/寫權限,因此您可能無法創建 f1.txt。 如果沒有適當的權限,請嘗試更改文件夾權限或用戶權限。 還要確保您在程序創建的同一位置完全找到該文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM