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();
        }
    }
  • 相关阅读:
    集合类学习之ArrayList源码解析
    集合类学习之Hashmap机制研究
    基于 HTTP/2 的全新 APNs 协议
    tcp协议头窗口,滑动窗口,流控制,拥塞控制关系
    TCP、UDP、IP 协议分析
    /proc/net/tcp中各项参数说明
    linux系统limit知识
    随机行
    nf_conntrack被启用导致服务故障
    HTTP 2.0的那些事
  • 原文地址:https://www.cnblogs.com/cxmsky/p/2886463.html
Copyright © 2011-2022 走看看