如何在Java中向txt文件发送X数量的数字?
我需要向Java中的txt文件发送X个数字,我有:如何在Java中向txt文件发送X数量的数字?,java,file-writing,Java,File Writing,我需要向Java中的txt文件发送X个数字,我有: for(int count = 0; count< amount; count++){ text =text + array[count] + "\n"; try( PrintWriter out = new PrintWriter( "nums.txt" ) ){ out.println(text);
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
。。。等等。通过颠倒逻辑。你有:
loop:
create and write to file
做:
相反
换句话说:for循环应该进入try语句;而不是在每个循环期间创建新的FileWriter
通常,Andy是正确的:您希望使用依赖于系统的换行符;因此,在您选择的操作系统上打开时,文件确实包含正确的换行符。您是在记事本中打开文件的,所以我猜您使用的是Windows
text =text + array[count] + "\r\n";
\r\n是Windows行分隔符
也可以使用System.getPropertyline.separator获取当前平台的行分隔符
或者您可以使用:
text += String.format("%s%n", array[count]);
也可以使用StringBuilder,这样可以避免以二次方式创建文本字符串:
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();
或者您可以使用更好的文本编辑器来处理*nix样式的行结尾。看看javadoc: 公共无效打印 通过写入行分隔符字符串终止当前行。这个 行分隔符字符串由系统属性定义 line.separator,并且不一定是单个换行符 “\n” 你在用哪个系统?您确定它正在添加正确的新行吗 另外,正如其他人提到的,您最好打开流,然后使用StringBuilder循环写入流
干杯。您的for循环应该在try块内,而不是相反方向。此外,使用bufferedwriter,您可以使用新行向文件中添加新行,而不是使用\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
您应该在循环外初始化PrintWriter!您知道吗,在每次迭代中,您都会向数组中添加一个数字,然后每次都写出整个数组?我知道,但没有注意到,谢谢!:汉克斯!我曾经\r:d密切关注SteveSmith对这个问题的评论。
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();
try(PrintWriter out = new PrintWriter("nums.txt")) {
for(int count = 0; count< amount; count++){
out.println(array[count]);
}
}
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