美文网首页
IO流文件读写与编码

IO流文件读写与编码

作者: 让你变好的过程从来都不会很舒服 | 来源:发表于2021-09-24 10:21 被阅读0次

一、文本的写入

        String name="张三你好";
        byte[] bytes = name.getBytes("UTF-8");
        // 文件路径
        File file = new File("explame.txt");
        OutputStream outputStream = new FileOutputStream(file);
        outputStream.write(bytes);
        outputStream.close();

二、文本的输出

// 用于接受数据的缓冲区
        byte[] buffer = new byte[1000];
        // 文件放在根目录下
        File file = new File("explame.txt");
        // 从文件中读取数据,放到缓冲区中
        InputStream inputStream = new FileInputStream(file);
        int n = inputStream.read(buffer, 0, 1000);
        inputStream.close();
        System.out.println("读取了"+n+"个字节");
        // 将前n个字节转成字符串
        String str= new String(buffer,0,n,"UTF-8");
        System.out.println("内容"+str);

中文乱码出现的本质原因:是解码方式不正确导致,在一段文本文字中,编码使用GBK进行编码,而你使用UTF8进行解码,解码和编码方式不一致,则会出现乱码问题

三、byte[] 和inputStream 相互转化

1:byte[]转换为InputStream

InputStream sbs = new ByteArrayInputStream(byte[] buf); 

2:InputStream转换为InputStreambyte[]

ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 
byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据 
int rc = 0; 
while ((rc = inStream.read(buff, 0, 100)) > 0) { 
swapStream.write(buff, 0, rc); 
} 
byte[] in_b = swapStream.toByteArray(); //in_b为转换之后的结果 

代码:

import java.io.ByteArrayInputStream;  
import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
  
public class ByteToInputStream {  
  
    public static final InputStream byte2Input(byte[] buf) {  
        return new ByteArrayInputStream(buf);  
    }  
  
    public static final byte[] input2byte(InputStream inStream)  
            throws IOException {  
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
        byte[] buff = new byte[100];  
        int rc = 0;  
        while ((rc = inStream.read(buff, 0, 100)) > 0) {  
            swapStream.write(buff, 0, rc);  
        }  
        byte[] in2b = swapStream.toByteArray();  
        return in2b;  
    }  
  
}

相关文章

  • IO流文件读写与编码

    一、文本的写入 二、文本的输出 三、byte[] 和inputStream 相互转化 1:byte[]转换为Inp...

  • pythoncookbook 第5章 文件与IO

    第5章 文件与IO 文件的读写 和io都要通过内存 重载系统的编码方式 5.1 读取文本 f=open('/tmp...

  • 【JavaSE(十三)】JavaIO流(中)

    1 IO流 1.1 IO流概述 Java中使用 IO流 来读取和写入,读写设备上的数据、硬盘文件、内存、键盘等等,...

  • 3.c++标准库

    8.IO库 IO类 三个头文件: iostream 定义了用于读写流的基本类型 fstream 定义了读写命名文件...

  • IO流简介

    io流的作用:读写设备上的数据,硬盘文件、内存、键盘、网络.... io流分类:输入流和输出流,字节流和字符流 字...

  • 31.Python:文件读写

    IO操作与读写文件 读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。不论哪种,一定...

  • Java IO流读写文件

  • Java—IO

    Java—IO流 1.IO—File常用API及文件编码 separator:名称分隔符,用来拼接文件路径path...

  • IO

    IO文件读写 输入流输出流字节流字节输入流 InputStream字节输出流 OutputStream字符流字符输...

  • JavaSE笔记(五)文件传输基础IO流

    文件的编码 File类 RandomAccessFile IO流分为输入流、输出流 还有字节流、字符流 Buffe...

网友评论

      本文标题:IO流文件读写与编码

      本文链接:https://www.haomeiwen.com/subject/diaogltx.html