![](/img/trans.png)
[英]Weird charcters in java class file when viewed in Notepad++ or 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: ** * ** * ****
記事本不會將簡單的換行符'\\n'
為換行符。 它使用回車+換行符"\\r\\n"
的“ Windows”格式來指定換行符。
您基本上需要執行以下操作之一:
\\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"
結合使用,程序將在運行的平台上執行適當的操作。
但是,安裝比記事本更精細的編輯器並不是一個壞主意。
我同意上面提供的其他答案。 只需一點設計指針,就可以增強整體思維。
我了解的是您正在創建一些數據,然后嘗試從中生成一些圖形。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.