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();
    }
}
原文地址:https://www.cnblogs.com/cxmsky/p/2886463.html