文件读取(个人作业完善)

这次要求数组从文件读取,并处理好可能的bug,第一眼感觉挺简单的,因为文本读取上学期学过,但是事实并没有那么简单,

代码如下

public static int[] toArrayByFileReader1(String name) {
        // 使用ArrayList来存储每行读取到的字符串
        File file = new File(name);
        judeFileExists(file);
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            FileReader fr = new FileReader(name);
            BufferedReader bf = new BufferedReader(fr);
            String str;
            // 按行读取字符串
            while ((str = bf.readLine()) != null) {
                arrayList.add(str);
            }
            bf.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对ArrayList中存储的字符串进行处理
        int length = arrayList.size();
        int[] array = new int[length];
        for (int i = 0; i < length; i++) {
            String s = arrayList.get(i);
            array[i] = Integer.parseInt(s);
             
        }
        // 返回数组
        return array;
    }
    public static void judeFileExists(File file) {
         if (file.exists()) {
             System.out.println("文件存在!");
                }
         else {
                      System.out.println("文件不存在!");
                      System.exit(0);
//                      try {
//                          file.createNewFile();
//                      } catch (IOException e) {
//                          // TODO Auto-generated catch block
//                          e.printStackTrace();
//                      }
                  }
          
              }

  

public static void main(String[] args) throws IOException{
        // TODO Auto-generated method stub
        int[] a = toArrayByFileReader1("shuzu.txt");
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
        int sum=0,m=0;
        int max = 0;
        int [] b=new int[30];
        for(int j=0;j<a.length;j++)
        {
              sum=sum+a[j];
              b[m]=sum;
              m++;            
        }
        for(int k=0;k<m;k++)
        {
            System.out.println("sum="+b[k]); 
        
        }
        max=b[0];
        for(int i=1;i<m;i++)
        {
            if(max<b[i])
            {
                max=b[i];
            }
        }
        System.out.println("max="+max);
    }

  

原文地址:https://www.cnblogs.com/liuxiaojieqqq/p/10615374.html