JAVA-文件字节输入流与输出流

实验要求:
编写一个应用程序,从文件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);
      }
    
   }
   
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值