[英]Java: Read integers from an existing text file and output to another file
[英]Read integers from a file and perform addition and output result to the same file using java
//hello.txt
1
2
3
4
5
我有上面的文件,但我按如下所示讀取文件並對其求和。 我需要將結果存儲在同一文件中而不替換內容。 我該怎么做呢?
package filereadwrite;
import java.util.*;
import java.io.File;
import java.io.IOException;
public class ReadFile
{
public static void main(String[] args)
throws IOException
{
Scanner textfile = new Scanner(new File("D:/hello.txt"));
filereader(textfile);
}
static void filereader(Scanner textfile) {
int sum = 0;
while(textfile.hasNextInt()) {
int nextInt = textfile.nextInt();
System.out.println(nextInt);
sum += nextInt;
}
System.out.println("Sum= "+sum);
}
}
使用FileWriter
將總和寫回到文件並按如下所示對其進行初始化:
FileWriter filewriter = new FileWriter("D:/hello.txt", true);
filewriter.write(String.valueOf(sum));
filewriter.flush();
filewriter.close();
根據java文檔
給定File
對象,構造一個FileWriter
對象。 如果第二個參數為true
,則字節將被寫入文件的末尾而不是開頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.