• Java学习——读写txt文件


    package HHH;
    import java.io.*;
    import static java.lang.System.out;
    
    public class OpenFile {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            
            try{
                FileInputStream rf = new FileInputStream("openFile.txt");
                FileOutputStream wf = new FileOutputStream("write.txt");
                int n=512;
                byte buffer[] = new byte[n];//buffer就是个byte类型数组
                while((rf.read(buffer,0,n) != -1) && (n>0))//读取输入流
                {
                    out.print(new String(buffer));//在屏幕中输出,强制转换成字符串
                    wf.write(buffer,0,buffer.length);
                    
                }
                out.println();
                rf.close();
                wf.close();
            }catch(IOException ioe){
                out.println(ioe);
            }catch(Exception e){
                out.println(e);
            }
        }
    
    }

     

    package HHH;
    
    import java.util.*;
    import java.io.*;
    
    public class ScannerTest2 {
    
        public static void main(String[] args) throws IOException
        {
            // TODO Auto-generated method stub
            double sum = 0.0;
            int count = 0;
            FileWriter fout = new FileWriter("text.txt");
            fout.write("2 2.2 3 3.3 4 4.5 done");
            fout.close();
            
            FileReader fin = new FileReader("text.txt");
            
            Scanner in = new Scanner(fin);
            while(in.hasNext())
            {
                if(in.hasNextDouble())
                {
                    System.out.println(in.nextDouble());
                    sum = sum + in.nextDouble();
                    count++;
                }
                else
                {
                    String str = in.next();
                    System.out.println(str);
                    if(str.equals("done"))
                    {
                        break;
                    }
                    else
                    {
                        System.out.println("文件格式错误");
                        return ;
                    }
                }
            }
            fin.close();
            System.out.println("文件中数据的平均数是:"+ sum / count);
        
        }
    }

  • 相关阅读:
    CopyOnWriteArrayList
    Gradle version 2.2 is required. Current version is 2.10
    install mysql on ubuntu
    A<T extends B> and A <? extends B>
    java event listeners and dispatcher
    git
    linux patch usage
    Codeforces Round #404 (Div. 2) C 二分查找
    dijkstra算法模板及其用法
    Sublime Text 3 快捷键精华版
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/9983804.html
Copyright © 2020-2023  润新知