java 文件io,[Java] 在Java中优雅地进行文件IO操作

Java IO 相关的类确实很多,但我们并不是所有的类都会用到,我们常用的也就是文件相关的几个类,如文件最基本的读写类 File 开头的、文件读写带缓冲区的类 Buffered 开头的类,对象序列化反序列化相关的类 Object 开头的类。

下面用几个例子来介绍Java IO的基础用法,二进制流的读写 与 字符流的读写

1.二进制流读写

import java.io.*;

import java.nio.charset.StandardCharsets;

//Java 二进制IO操作 Titan 2020-03-25

public class BinaryIO {

public static void main(String[] args) throws IOException {

//IO写二进制数据

byte[] binaryData = "HelloWorld".getBytes(StandardCharsets.UTF_8);

writeBinary(binaryData);

//IO读二进制数据

String str = new String(binaryData, StandardCharsets.UTF_8);

System.out.println(str);

}

public static void writeBinary(byte[] data) throws IOException {

try (FileOutputStream fileOutSt = new FileOutputStream("Binary.dat")) {

fileOutSt.write(data);

}

}

public static byte[] readBinary() throws IOException {

try (FileInputStream fileInSt = new FileInputStream("Binary.dat")) {

return fileInSt.readAllBytes();

}

}

}

2. 字符流读写

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

//字符流IO操作 By Titan 2020-03-25

public class CharIO {

public static void main(String[] args) throws IOException {

//字符流IO写操作

writeChars("HelloWorld");

//字符流IO读操作

String str = readChars();

System.out.println(str);

}

public static void writeChars(String text) throws IOException {

try (FileWriter fw = new FileWriter("Text.txt")) {

fw.write(text);

}

}

public static String readChars() throws IOException {

String temp;

StringBuilder Str = new StringBuilder();

try (FileReader fr = new FileReader("Text.txt"); BufferedReader br = new BufferedReader(fr)) {

while ((temp = br.readLine()) != null) {

Str.append(temp);

}

} catch (IOException e) {

e.printStackTrace();

}

return Str.toString();

}

}

总结

本文只介绍了Java中IO的基础操作与如何优雅的进行IO异常的处理,其实Java.IO库中还有一些类可以实现更高端的玩法,比如RandomAccessFile能够实现高性能的文件随机读写,ObjectInputStream/ObjectOutputStream能够将对象进行序列化和反序列化文件存储等等,有兴趣可以进一步探索。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值