zoukankan      html  css  js  c++  java
  • 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);
        
        }
    }

  • 相关阅读:
    Linux驱动之USB(个人)
    iptables命令使用详解
    python操作mysql——mysql.connector
    linux下NFS实战
    CentOS6上ftp服务器搭建实战
    CentOS7下mariadb日常管理
    CentOS7配置httpd虚拟主机
    httpd常见配置
    常见加密算法
    HTTP安全通信:Https和SSL
  • 原文地址:https://www.cnblogs.com/caiyishuai/p/9983804.html
Copyright © 2011-2022 走看看