栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

文件读写IO流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

文件读写IO流

一 .读取文本

1.常用按行读取支持中文

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class MyReadFile {
    public static void main(String[] args) throws Exception {
        String path = "F:\IdeaProject\test\src\main\java\read\1.txt";
        File file = new File(path);
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStreamReader read = new InputStreamReader(fileInputStream, "UTF-8");//考虑到编码格式
        BufferedReader bufferedReader = new BufferedReader(read);
        String lineTxt;
        while ((lineTxt = bufferedReader.readLine()) != null) {//读取一行
            System.out.println(lineTxt);
        }
        bufferedReader.close();//先打开的后关闭
        read.close();
        fileInputStream.close();
    }
}

2.按行简洁读取(JDK1.8) 支持中文

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class MyReadFile {
    public static void main(String[] args) throws Exception {
        String path = "F:\IdeaProject\test\src\main\java\read\1.txt";//JDK1.8
        Stream lines = Files.lines(Paths.get(path));
        lines.forEach(line->{System.out.println(line);});
    }
}

二. 写入文本

import java.io.File;
import java.io.FileOutputStream;
public class MyWriteRead {
    public static void main(String[] args) throws Exception {
        String path = "F:\IdeaProject\test\src\main\java\read\1.txt";
        File file = new File(path);
        FileOutputStream fileOutputStream = new FileOutputStream(file, true);//true标识是否追加写入
        fileOutputStream.write("qwe%&&#()*)(&*n(^中文123123".getBytes("UTF-8"));//换行写入使用 "n"
        fileOutputStream.close();//先打开的后关闭
    }
}

三 .读取二进制文件

import java.io.*;
public class MyReadFile {
    public static void main(String[] args) throws Exception {
        String source = "F:\IdeaProject\test\src\main\java\read\1.txt";
        int length = 512;//读取缓冲大小
        byte[] buffer = new byte[length]; //缓冲区字节数组
        File sourceFile = new File(source);
        InputStream fis = new FileInputStream(sourceFile);
        BufferedInputStream bis = new BufferedInputStream(fis, length);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//字节缓冲流数组
        long fileSize = sourceFile.length(); // 文件总字节数
        int haveRead = 0; // 已读取字节数
        int readSize; // 记录每次实际读取字节数
        while (null != bis && (readSize = bis.read(buffer)) != -1) {
            haveRead += readSize;
            byteArrayOutputStream.write(buffer, 0, readSize);
            System.out.println("已经读取: " + haveRead + " Byte 完成" + haveRead * 100 / fileSize + "% 单次读取:" + readSize + " Byte");
        }
        byte[] result = byteArrayOutputStream.toByteArray();//结果内容  大文件读取注意内存溢出
        bis.close();
        System.out.println("读取完成: " + haveRead);
        System.out.println("字节转字符串内容如下: " + new String(result));
    }
}

四.写二进制文件

import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.nio.charset.Charset;
public class MyWriteFile {
    public static void main(String[] args) throws Exception {
        String file= "F:\IdeaProject\test\src\main\java\read\2.txt";
        FileOutputStream fos = new FileOutputStream(file, true);//是否追加写入
        BufferedOutputStream bos = new BufferedOutputStream(fos,1024);//缓冲大小
        byte[] bytes = "123456789".getBytes(Charset.forName("UTF-8"));
        bos.write(bytes);//写入bytes中全部内容
        bos.write(bytes, 0, 2);//写入bytes中从0开始长度为3的字节数据
        bos.flush();//刷新
        bos.close();//释放资源
        System.out.println("写入完成");
    }
}

五 .合并多个视频文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
public class MyWriteRead {
    public static void main(String[] args) throws Exception {
        String source = "F:\IdeaProject\test\src\test\java";//视频文件列表,此目录下有多个视频文件
        String destination = "F:\IdeaProject\test\src\main\java\read\result.mp4";//合并之后之后的文件
        File[] files = new File(source).listFiles();
        int index = 1;//进度记录
        int bufferSize = 4096; // 设置缓冲区大小
        byte buffer[] = new byte[bufferSize]; // 缓冲区字节数组
        for (File sourceFile : files) {
            FileInputStream read = null;BufferedInputStream byteRead = null;
            FileOutputStream write = null;BufferedOutputStream byteWrite = null;
            try {
                read = new FileInputStream(sourceFile);
                byteRead = new BufferedInputStream(read, bufferSize);
                write = new FileOutputStream(destination, true);//追加
                byteWrite = new BufferedOutputStream(write, bufferSize);
                int readSize; // 记录每次实际读取字节数
                while (null != byteRead && (readSize = byteRead.read(buffer)) != -1) {
                    byteWrite.write(buffer, 0, readSize);
                }
                byteWrite.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {close(byteRead);close(read);close(byteWrite);close(write);}
            System.out.println("进度:"+index++ +"/"+files.length);
        }
        System.out.println("合并完成");
    }
    public static void close(Object obj) {
        try {
            if (obj instanceof FileInputStream) {((FileInputStream) obj).close();return;}
            if (obj instanceof BufferedInputStream) {((BufferedInputStream) obj).close();return;}
            if (obj instanceof FileOutputStream) {((FileOutputStream) obj).close();return;}
            if (obj instanceof BufferedOutputStream) {((BufferedOutputStream) obj).close();return;}
            throw new Exception("没有找到资源类型,无法正常关闭");
        } catch (Exception e) {
            StringBuffer sbr = new StringBuffer("关闭失败").append(obj.getClass()).append("n").append(e.getMessage());
            System.out.println(sbr);//异常原因
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/755395.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号