要求:
编写一个应用程序,从文件a.txt中读取数据,筛选出文件中的数字字符,并将其转换成double类型是,对所有的数据求和,并求出平均值,把数据数组与计算结果输出到文件b.txt中。
如图:
代码:
import java.io.*;
import java.util.Arrays;
public class test {
public static void main(String args[]) {
int n=-1;
String str = null;
File file=new File("b.txt");
double sum=0,average;
//读数据
try{
File f=new File("D:\\软件\\JAVA实验\\实验11","a.txt");
InputStream in = new FileInputStream(f);
int size=(int) f.length();
byte [] a=new byte[size];
while((n=in.read(a,0,size))!=-1) {
String s=new String (a,0,n);
System.out.println("a文件中的内容是:"+s);
str=s;
}
in.close();
}
catch(IOException e) {
System.out.println("File read Error"+e);
}
String regex="\\D+";
String array[]=str.split(regex);
int b[]=new int[array.length];
double B[]=new double[array.length];
for(int j=0;j<array.length;j++){
b[j]=Integer.parseInt(array[j]);
sum=sum+b[j];
B[j]=b[j];
}
average=sum/b.length;
System.out.println("b数据是"+Arrays.toString(b));
try{//写数据
file.createNewFile();
OutputStream out=new FileOutputStream(file);
String x="写入文件b.txt的数据是"+Arrays.toString(B);
String y="sum="+String.valueOf(sum)+" ";
String z="平均值是"+String.valueOf(average);
byte []X=x.getBytes();
byte []Y=y.getBytes();
byte []Z=z.getBytes();
out.write(X);
out.write(Y);
out.write(Z);
out.close();
File f2=new File("D:\\软件\\JAVA实验\\实验11","b.txt");
InputStream in2 = new FileInputStream(f2);
int size=(int) f2.length();
byte [] a2=new byte[size];
while((n=in2.read(a2,0,size))!=-1) {
String s2=new String (a2,0,n);
System.out.println(s2);
}
in2.close();
}
catch(IOException e){
System.out.println("File write Error"+e);
}
}
}