簡體   English   中英

用Java寫入文件:NotePad與Word / WordPad / NotePad ++的輸出顯示不同

[英]Writing to File in Java: output displays differently in NotePad vs. Word/WordPad/NotePad++

以下是Java代碼,用於讀取名為Sales.txt的現有文本文件並將條形圖輸出至名為storeReport.txt的文本文件
每個星號代表$ 100的銷售額。

導入java.io. *;

導入java.util。*;

公共課BarChart

{public static void main(String [] args)拋出FileNotFoundException,IOException

   {
       int[] s = new int[5];
       int[] b = new int[5];

       FileWriter fstream = new FileWriter("storeReport.txt");
       BufferedWriter out = new BufferedWriter(fstream);
       Scanner scanner = new Scanner(new File("Sales.txt"));

   int i = 0;

       while(scanner.hasNext())
       s[i++] = scanner.nextInt();
         System.out.println("SALES BAR CHART\n");
         out.write("SALES BAR CHART\n");

   for (i=0; i<s.length; i++)
       {
        b[i] = s[i]/100;
        out.write("store "+ (i+1) +" : ");
        System.out.print("store "+ (i+1) +" : ");

        for(int j = 1; j <= b[i]; j++) {
          System.out.print("*");
          out.write("*"); }
          out.write("\n");
          System.out.println();
       }

        out.close();  //Close the output stream

}
}

當我在Word,WordPad或NotePad ++中打開storeReport.txt時,輸出將按預期顯示:

商店1: * **
商店2: ** * **
商店3: * ** * ** * *
商店4: * *
商店5: * ** * ** * **

當我在NotePad中打開文件時,輸出全部顯示在一行上。 (我使用Windows 7和最新的jGrasp來編譯和運行該程序。)

輸入文件Sales.txt的內容如下:

1000
1200
1800
800
1900年

任何人都知道為什么記事本將輸出顯示為:

SALES BAR CHART 商店 1: * ** 商店2: ** * * 商店3: ** * ** * ** 商店4: ** 商店5: ** * ** * ****

我懷疑這是換行問題。 嘗試更換您的

out.write("\n");

out.newLine();

記事本不會將簡單的換行符'\\n'為換行符。 它使用回車+換行符"\\r\\n"的“ Windows”格式來指定換行符。

您基本上需要執行以下操作之一:

  1. 停止使用記事本
  2. 使用某些程序將行尾字符轉換為CR + LF( unix2dos
  3. 更改程序以輸出\\r\\n

我想大多數人都會同意#1是您的最佳選擇,但是我對Windows平台上\\r\\n問題的延伸范圍了解不多。

編輯:正如srgerg在他的回答中指出的那樣,最好的選擇是停止自行指定\\n並使用JAVA的out.newLine()函數產生行尾。 這些對於您使用的任何平台都是正確的。

有關更多信息,請參見Wikipedia: http : //en.wikipedia.org/wiki/Newline#Common_problems

記事本僅了解DOS / Windows的行尾,即\\ r \\ n,而記事本++和Wordpad也處理Linux / Unix /新MacOS(\\ n)和較舊的MacOS(\\ r)行尾。

您可以嘗試為系統找到正確的行尾:

System.getProperty ("line.separator");

或者嘗試將println ()printf/format"%n"結合使用,程序將在運行的平台上執行適當的操作。

但是,安裝比記事本更精細的編輯器並不是一個壞主意。

我同意上面提供的其他答案。 只需一點設計指針,就可以增強整體思維。

我了解的是您正在創建一些數據,然后嘗試從中生成一些圖形。

  1. 如何使用顯式字段分隔符和記錄分隔符。
  2. 使用一些編碼。 如果它在不同的環境中運行,這將為您提供更好的控制。

暫無
暫無

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

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