java文件读写及字符串分割

1.介绍 

  用java语言实现文件(支持各种文件类型)读写,将字符串分割处理后输出。

2.代码

         /* 1.读入TXT文件 */  
        String pathname = ".//data//"+args[0]+".minion"; //注意要用双斜杠,运行时(run as)--(run configuration)--对Main+Arguments进行相应配置
       // String pathname = ".//data//input.minion"; //直接点击运行
        File filename = new File(pathname); // 要读取以上路径的文件  
        InputStreamReader reader = new InputStreamReader(new FileInputStream(filename)); // 建立一个输入流对象
        BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言  
        
        /*2.按行读取文件,同时分割字符串*/
        int AtoD=0;
        int CtoDNoRing=0;
        int AllDel=0;
        String line = "";  
        line = br.readLine();  
        while (line != null) {  
            AtoD=AtoD+Integer.parseInt(line.split(" ")[3]);
            CtoDNoRing=CtoDNoRing+Integer.parseInt(line.split(" ")[4]);
            AllDel=AllDel+Integer.parseInt(line.split(" ")[5]);
           
            line="";
            line = br.readLine(); // 一次读入一行数据  
        }  
        System.out.println(pathname+" "+AtoD+" "+CtoDNoRing+" "+AllDel);
      
        /* 3.写入Txt文件 */  
        BufferedWriter writer = new BufferedWriter(new FileWriter("AccuracyResult.txt", true));
        writer.write(pathname+" "+AtoD+" "+CtoDNoRing+" "+AllDel);
        writer.newLine();
        writer.flush();

        writer.close();

3.数据格式

45 200 7471 7 0 7

45 200 7241 14 0 14

45 200 6992 6 0 6

每行有5个数据,用空格隔开。

目的是将每一列相加,只取后三个数据

猜你喜欢

转载自blog.csdn.net/u014714362/article/details/79665051