• I/O流


    0. 字节流与二进制文件

    我的代码

    package experiment0;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args)
        {
            String fileName="d:\student.data";//文件地址
            try(DataOutputStream dos=new DataOutputStream(new FileOutputStream(fileName)))//写入二进制文件
            {
                Student student1=new Student(1,"xixi",19,89);
                dos.writeInt(student1.getId());
                dos.writeUTF(student1.getName());
                dos.writeInt(student1.getAge());
                dos.writeDouble(student1.getGrade());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("ojk");
            try(DataInputStream dis=new DataInputStream(new FileInputStream(fileName)))//读取文件并输出
            {
                int id=dis.readInt(),age=dis.readInt();
                String name=dis.readUTF();
                double grade=dis.readDouble();
                Student student2=new Student(id,name,age,grade);//存入对象
                System.out.println(student2.toString());//输出
            } catch (FileNotFoundException e) {
                
                e.printStackTrace();
            } catch (IOException e) {
               
                e.printStackTrace();
            }
        }
    }
    

    二进制与文本,前者是数据的原形式后者是数据的终端形式。
    在使用try...catch...finally时要避免在finally中使用return 语句或者抛出异常.

    1. 字符流与文本文件:使用 PrintWriter(写),BufferedReader(读)

    1.1使用BufferedReader从编码为UTF-8的文本文件中读出学生信息,并组装成对象然后输出。

    package expriment1_1;
    
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;
    
    public class main {
    
    	public static void main(String[] args) {
    		String fileName="d:\Students.txt";//文件地址
    		List<Student> studentList = new ArrayList<>();//以Student对象 的list
    		        try(
    		            FileInputStream fis=new FileInputStream(fileName);
    		            InputStreamReader isr=new InputStreamReader(fis, "UTF-8");//转换流
    		            BufferedReader br=new BufferedReader(isr))
    		        {
    		            String line=null;
    		            while((line=br.readLine())!=null)
    		            {
    		                String[] msg=line.split("\s+");
    		                int id=Integer.parseInt(msg[0]);
    		                String name=msg[1];
    		                int age=Integer.parseInt(msg[2]);
    		                double grade=Double.parseDouble(msg[3]);
    		                Student stu=new Student(id,name,age,grade);
    		                studentList.add(stu);
    		            } 
    		        } 
    		        catch (FileNotFoundException e)
    		        {
    		          
    		            e.printStackTrace();
    		        } 
    		        catch (IOException e) 
    		        {
    		            
    		            e.printStackTrace();
    		        }
    		        System.out.println(studentList);
    
    	}
    
    }
    

    1.2编写public static ListreadStudents(String fileName);从fileName指定的文本文件中读取所有学生,并将其放入到一个List中

    public static List<Student> readStudents(String fileName)
        {
            List<Student> studentList = new ArrayList<>();
            try(
                FileInputStream fis=new FileInputStream(fileName);
                InputStreamReader isr=new InputStreamReader(fis, "UTF-8");
                BufferedReader br=new BufferedReader(isr))
            {
                String line=null;
                while((line=br.readLine())!=null)
                {
                    String[] msg=line.split("\s+");
                    int id=Integer.parseInt(msg[0]);
                    String name=msg[1];
                    int age=Integer.parseInt(msg[2]);
                    double grade=Double.parseDouble(msg[3]);
                    Student stu=new Student(id,name,age,grade);
                    studentList.add(stu);
                }
            } 
            catch (FileNotFoundException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            catch (IOException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return studentList;
        }
    

    1.3使用PrintWriter将Student对象写入文本文件,基础代码见后。注意:缓冲区问题。

    package experime1_3;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    
    public class main {
    
    	public static void main(String[] args) {
    		String fileName="d:\Students.txt";
    		try(
    		            FileOutputStream fos=new FileOutputStream(fileName,true);
    		            OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8");
    		            PrintWriter pw=new PrintWriter(osw))
    		        {
    		            pw.println();
    		            pw.print("4 小羊 12 88");
    		        } catch (FileNotFoundException e) {
    		            // TODO Auto-generated catch block
    		            e.printStackTrace();
    		        } catch (IOException e) {
    		            // TODO Auto-generated catch block
    		            e.printStackTrace();
    		        }
    
    	}
    
    }
    

    1.4使用ObjectInputStream/ObjectOutputStream读写学生对象

    package experiment1_4;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    import experiment0.Student;
    
    public class main {
    
    	public static void main(String[] args) {
    		String fileName1="d:\Students.dat";
    		try(
    		            FileOutputStream fos=new FileOutputStream(fileName1);
    		            ObjectOutputStream oos=new ObjectOutputStream(fos))
    		        {
    		            Student ts=new Student(5,"asd",14,60);
    		            oos.writeObject(ts);
    		        }
    		        catch (Exception e) {
    		            // TODO Auto-generated catch block
    		            e.printStackTrace();
    		        }
    		        try(
    		            FileInputStream fis=new FileInputStream(fileName1);
    		            ObjectInputStream ois=new ObjectInputStream(fis))
    		        {
    		            Student newStudent =(Student)ois.readObject();
    		            System.out.println(newStudent);
    		        } catch (IOException e) {
    		            // TODO Auto-generated catch block
    		            e.printStackTrace();
    		        } catch (ClassNotFoundException e) {
    		            // TODO Auto-generated catch block
    		            e.printStackTrace();
    		        }
    
    	}
    
    }
    
    

    使用程序生成的文件是支持UTF-8
    方法writeObject处理对象的序列化

    2缓冲流(结合使用JUint进行测试)

    对文件进行1000万次写入

    String FILENAME = "D:\test.txt";    
            double sum=0,aver;
            PrintWriter pw=null;
            try {
                pw = new PrintWriter(FILENAME);
                for(int i = 0;i<1000_0000;i++){//写入1千万行
                int x=new Random().nextInt(10);
                sum+=x;
                pw.println(x);
                //System.out.println(x);
            }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally{
                pw.close();
            }
            aver=sum/10000000;
            System.out.format("%.6f", aver);
    

    JUnit

    public class test {
        @Test
            public void test() {
            String FILENAME = "test.txt";
            long begin = System.currentTimeMillis();
            Scanner scanner=null;
            try {
                scanner = new Scanner(new File(FILENAME));
                while(scanner.hasNextLine()){//只是读出每一行,不做任何处理
                    scanner.nextLine();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally{
                scanner.close();
            }       
            System.out.println("1 ok");
        }
        @Test
        public void Bufftest() {
            String FILENAME = "test.txt";
            long begin = System.currentTimeMillis();
            BufferedReader br = null;
            try {
                 br = new BufferedReader(new FileReader(new File(FILENAME)));
                while(br.readLine()!=null){};//只是读出,不进行任何处理
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }       
            System.out.println("2 ok");
        }
    }
    

    在进行JUnit测试是要注意测试方法必须使用public void进行修饰,不能带任何的参数
    并且要新建一个源代码目录来存放我们的测试代码

    3. 字节流之对象流

    public static void writeStudent(List<Student> stuList)
        {
            String fileName="d:\Students.dat";
            try (   FileOutputStream fos=new FileOutputStream(fileName);
                    ObjectOutputStream ois=new ObjectOutputStream(fos))
            {
                ois.writeObject(stuList);
                
            } 
            catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    public static List<Student> readStudents(String fileName)
        {
            List<Student> stuList=new ArrayList<>();
            try (   FileInputStream fis=new FileInputStream(fileName);
                    ObjectInputStream ois=new ObjectInputStream(fis))
            {
                stuList=(List<Student>)ois.readObject();
            } 
            catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return stuList;
        }   
    

    当使用对象流写入或者读取对象的时候,必须保证该对象是序列化的,这样是为了保证对象能够正确的写入文件,并能够把对象正确的读回程序。

    5. 文件操作

    public static void findFile(Path dir,String fileName) {
    		File file = dir.toFile();
    		File[] files=file.listFiles();
    		for(File f:files)
            {
                if(f.isFile())
                {
                    if(f.getName().equals(fileName))
                    {
                        System.out.println(f.getAbsolutePath());
                        return;
                    }
                }
                else if(f.isDirectory())
                {
                    findFile(f.toPath(),fileName);
                }
            }
    	}
    

    在查阅资料File类和Path类之间是可以互相转换

    6. 正则表达式

    6.1如何判断一个给定的字符串是否是10进制数字格式?尝试编程进行验证。

    public class Main {
    
        public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            Pattern pattern=Pattern.compile("^[+-]?[0-9]+(\.\d+)?");
            Matcher matcher=null;
            while(sc.hasNext())
            {
                String str=sc.next();
                matcher=pattern.matcher(str);
                System.out.println(matcher.matches());
            }
            sc.close();
        }
    }
    

    6.2修改HrefMatch.java

    package experiment6_2;
    
    import java.io.*;
    import java.net.*;
    import java.util.regex.*;
    
    /**
     * This program displays all URLs in a web page by matching a regular expression that describes the
     * <a href=...> HTML tag. Start the program as <br>
     * java HrefMatch URL
     * @version 1.01 2004-06-04
     * @author Cay Horstmann
     */
    public class HrefMatch
    {
       public static void main(String[] args)
       {
    	   try
    	      {
    	         // get URL string from command line or use default
    	        /* String urlString;
    	         if (args.length > 0) urlString = args[0];
    	         else urlString = "http://cec.jmu.edu.cn";*/
    	         String fileName="F:\计算机语言的学习文件\JAVA 学习资料\下载文件\Exp-StreamAndFile\Exp-StreamAndFile\参考代码\HrefMatch\集美大学-计算机工程学院.htm";
    	         // open reader for URL
    	        //InputStreamReader in = new InputStreamReader(new URL(urlString).openStream());
    	        InputStreamReader in = new InputStreamReader(new FileInputStream(fileName));
    	    //InputStreamReader in = new InputStreamReader(new FileInputStream("集美大学-计算机工程学院.htm"));
    	         // read contents into string builder
    	         StringBuilder input = new StringBuilder();
    	         int ch;
    	         while ((ch = in.read()) != -1)
    	            input.append((char) ch);
    
    	         // search for all occurrences of pattern
    	         String patternString = "<a\s+href\s*=\s*("[^"]*"|[^\s>]*)\s*>";
    	     String patternImgString = "[+-]?[0-9]+";
    	     //String patternString = "[u4e00-u9fa5]";     //匹配文档中的所有中文
    	         Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
    	         Matcher matcher = pattern.matcher(input);
    
    	         while (matcher.find())
    	         {
    	            int start = matcher.start();
    	            int end = matcher.end();
    	            String match = input.substring(start, end);
    	            System.out.println(match);
    	         }
    	      }
    	      catch (IOException e)
    	      {
    	         e.printStackTrace();
    	      }
    	      catch (PatternSyntaxException e)
    	      {
    	         e.printStackTrace();
    	      }
       }
    }
    
    

    总的来说这些都是课上有完成的内容,但是量比较多,回来后也有些遗忘,在写这些的时候花费了很多时间才完成!

  • 相关阅读:
    分布式事务框架seata入门
    生活==不易
    LR Socket接收超时TPS上不去解决方法
    Loadrunner拼装(并发用户)唯一值方法
    shell/Python复制文件和文件夹
    redis可以设置过期key回调实现延时队列
    计算机USB读写权限统一管理(在域环境中)
    微软Win10最新BUG_2021年9月15日_KB5005565更新之后打印机突然连接不上 或 不能打印0x0000011b(附解决方案)!
    SQLServer中update没带where的回滚操作(Update或者Delete误操作恢复方法)
    107.如何用Windows Defender全盘扫描
  • 原文地址:https://www.cnblogs.com/jellysheep/p/11938913.html
Copyright © 2020-2023  润新知