簡體   English   中英

如何將X數量的數字發送到Java中的txt文件?

[英]How can i send a X amount of numbers to a txt file in Java?

我需要將X數字發送到Java中的txt文件中,我有這個:

for(int count = 0; count< amount; count++){                             
           text =text + array[count] + "\n";
           try(  PrintWriter out = new PrintWriter( "nums.txt" )  ){
                out.println(text);
            }//end try
           catch (FileNotFoundException ex) { 
Logger.getLogger(MainPage.class.getName()).log(Level.SEVERE,null, ex);
            }//end catch
        }// end for

問題是txt文件如下所示: 1500個號碼:

我該如何打印上一個?

我的意思是:

1
2
3

... 等等。

您正在記事本中打開文件,所以我想您正在使用Windows。

text =text + array[count] + "\r\n";

\\r\\n是Windows的行分隔符。

或者,您可以使用System.getProperty("line.separator")獲取當前平台的行分隔符。

或者您可以使用:

text += String.format("%s%n", array[count]);

或者,您可以使用StringBuilder ,它避免二次創建text String:

StringBuilder sb = new StringBuilder();
for(int count = 0; count< amount; count++){
  sb.append(array[count]);
  sb.append(System.getProperty("line.separator"));
}
String text = sb.toString();

或者,您可以簡單地在循環中進行打印,從而完全避免創建text String:

try(PrintWriter out = new PrintWriter("nums.txt")) {
  for(int count = 0; count< amount; count++){                             
    out.println(array[count]);
  }
}

或者,您可以使用更好的文本編輯器來實際處理* nix樣式的行尾。

通過顛倒你的邏輯。 你有:

loop:
  create and write to file

做:

create new file
loop:
  write to file

代替。

換句話說:您的for循環應該進入 try語句; 而不是在每個循環中創建一個新的FileWriter()。

通常,Andy是正確的:您想使用“依賴於系統的”換行符; 因此,在您選擇的操作系統上打開文件時,該文件確實包含正確的換行符。

看看javadoc:

public void println()

通過寫入行分隔符字符串來終止當前行。 行分隔符字符串由系統屬性line.separator定義,不一定是單個換行符('\\ n')。

您在哪個系統上工作? 您確定要添加適當的新行嗎?

另外,正如其他人所述,您最好打開流,然后循環使用StringBuilder對其進行寫入。

干杯。

您的for循環應位於try塊內,而不是相反。 同樣,使用bufferedwriter,您可以使用newLine()向文件中添加新行,而不是使用\\ n。

try(BufferedWriter bw = new BufferedWriter(new FileWriter("nums.txt", true))){
    for (int count = 0; count < amount; count++) {                             
        text += array[count];
        bw.write(text);
        bw.newLine();
    }
}
catch (FileNotFoundException ex) {

    Logger.getLogger(MainPage.class.getName()).log(Level.SEVERE,null, ex);
     }//end catch

暫無
暫無

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

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