将读取的内容通过分隔符“|”转换为 int数组后并计算所有元素的和,并将结果保存到result.txt文件中,保存的结果如: number1 + number2 + number3 + number4 = total (每个元素的通过”+”相连)
testData.txt中的内容是:
1|2|3|4|5|6|7|8|9|10
11|12|13|14|15|16|17|18|19|20
21|22|23|24|25|26|27|28|29|30
package com.chinasofti.java616;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Add {
public static void main(String[] args) {
BufferedReader br=null;
BufferedWriter bw=null;
try {
br=new BufferedReader(new FileReader("D:/me/testData.txt"));
bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:/me/result.txt")));
StringBuilder sb=new StringBuilder();
String st=null;
int sum=0;
while((st=br.readLine())!=null){
String[] s=st.split("\|");
for(int i=0;i<s.length;i++){
sb.append(s[i]);
sb.append("+");
sum+=Integer.parseInt(s[i]);
}
}
sb.deleteCharAt(sb.length()-1);
sb.append("=");
sb.append(sum);
System.out.println(sb);
bw.write(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(br!=null){
br.close();
}
if(bw!=null){
bw.flush();
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
结果:
1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+
21+22+23+24+25+26+27+28+29+30=465