这周我们老师布置了在上一周的基础上实现文件的存储以及读取,刚开始我先将文件存储以及相关的程序写出来,通过询问老师发现对于数组空间的定义可以使用变量形式,经过这个方法我完成了对任意大小的数据可以进行储存以及读取,之后有听取其他同学的惊讶能使用biginteger类来实现大数据的存储。
源代码:
package lianxi; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.util.Scanner; public class App7 { public static void main(String[] args) throws IOException { Scanner in= new Scanner(System.in); //writeFile(); int hang=gethang(); String[] num=getnum(hang); String[] num2=new String [hang]; String max="0"; BigInteger bi,bi2; int s; boolean f=false; for(s=0;s<num.length;s++) { if(num[s]==null)break; bi=new BigInteger (num[s]); if(bi.max(BigInteger.valueOf(0))!=BigInteger.valueOf(0))f=true; } if(f==true) { max=num[0]; num2[0]=num[0]; for(int i=1;i<s;i++) { //num2[i]=num2[i-1]+num[i]; bi=new BigInteger (num[i]); bi2=new BigInteger (num2[i-1]); num2[i]=""+bi2.add(bi); if(bi.max(bi2)==bi)max=num2[i]; } for(int i=0,j=0;j<s;) { //循环减去第一个 bi=new BigInteger (num2[i]); bi2=new BigInteger (num[j]); bi=bi.subtract(bi2); if(bi.max(bi2)==bi)max=num2[i]; if(i==s-1) {j++;i=j;} else i++; } } else { max=num[0]; num2[0]=num[0]; for(int i=1;i<s;i++) { num2[i]=num2[i-1]+num[i]; bi=new BigInteger (num[i]); bi2=new BigInteger (num[i-1]); if(bi.max(bi2)==bi)max=num2[i]; } } System.out.println(max); //add(); in.close(); } public static int gethang() { int i=0; try (FileReader reader = new FileReader("text.txt"); BufferedReader br = new BufferedReader(reader)) { String line; while ((line = br.readLine()) != null) { i++; } } catch (IOException e) { e.printStackTrace(); } return i; } public static String[] getnum(int lang) throws IOException { String [] in=new String[lang]; int i=0; try (FileReader reader = new FileReader("text.txt"); BufferedReader br = new BufferedReader(reader)) { String line; while ((line = br.readLine()) != null) { in[i]= line; i++; } } catch (IOException e) { e.printStackTrace(); } return in; } public void writeFile() { int i=0; int fu=0; try { File writeName = new File("text.txt"); writeName.createNewFile(); try (FileWriter writer = new FileWriter(writeName); BufferedWriter out = new BufferedWriter(writer) ) { for(int j=0;j<150;j++) { i=1+(int)(Math.random()*9); //fu=1+(int)(Math.random()*2); //if(fu==1)i=0-i; out.write(i+" "); // 换行 out.flush(); } } } catch (IOException e) { e.printStackTrace(); } } public static void add() throws IOException { int i=0; try (FileReader reader = new FileReader("text.txt"); BufferedReader br = new BufferedReader(reader)) { String line; while ((line = br.readLine()) != null) { i+=Integer.parseInt(line); } } catch (IOException e) { e.printStackTrace(); } System.out.println("sum="+i); } }