zoukankan      html  css  js  c++  java
  • Java基础之IO流,以字节流的方式操作读写文件FileOutputStream和FileInputStream的使用

    import java.io.*;
    import java.text.*;
    import java.util.*;
    class FileOutputStreamDemo
    {
        public static void main(String[] args) throws IOException
        {
            writeFile(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S E").format(new Date()));
            readFile_1();
        }
        
        //小文件便捷读取方式,大文件禁用
        public static void readFile_3() throws IOException
        {
            FileInputStream fis = new FileInputStream(new File("demo.txt"));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            
            System.out.println(new String(buffer));
        }
        
        //按字节数组读取文件
        public static void readFile_2() throws IOException
        {
            FileInputStream fis = new FileInputStream(new File("demo.txt"));
            
            byte[] buffer = new byte[1024];
            int length = 0;
            
            while((length=fis.read(buffer))!=-1)
            {
                System.out.println(new String(buffer,0,length));
            }
            
            fis.close();
        }
        
        //按单个字节读取文件
        public static void readFile_1() throws IOException
        {
            FileInputStream fis = new FileInputStream(new File("demo.txt"));
            int ch = 0;
            while((ch=fis.read())!=-1)
            {
                System.out.print((char)ch);
            }
            
            fis.close();
        }
        
        //以字节流的方式写入文件
        public static void writeFile(String data) throws IOException
        {
            FileOutputStream fos = new FileOutputStream(new File("demo.txt"));
            fos.write(data.getBytes());
            fos.close();
        }
    }
  • 相关阅读:
    Java注解学习
    微信小程序开发的一些基础知识点
    feign请求传送实体类参数的一些摸索
    springcloud bus中踩过的坑
    API网关初接触
    ELKF学习(Elasticsearch+logstash+kibana+filebeat)
    getWriter() has already been called for this response异常的一些问题
    kafka的学习
    如何优化一个丑陋的switch语句!
    项目启动之后进行一些初始化的方法
  • 原文地址:https://www.cnblogs.com/cxmsky/p/2886463.html
Copyright © 2011-2022 走看看