java IO

本文详细介绍了Java中的输入输出流(IO流),包括InputStream与OutputStream的各种实现类及其使用方法,如FileInputStream、BufferedInputStream等,并提供了典型的文件读写示例代码。此外,还概述了Commons IO工具类的功能,如IOUtils和FileUtils,这些工具类极大地简化了日常的文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

InputSteam & OutputSteam

  • InputStream (InputStreamReader)

BufferedInputStream : used as other input stream's wrapper.
ByteArrayInputStream : new ByteArrayInputStream(byteContent), A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.
FileInputStream : new FileInputStream(path); read file

//seldom use
DataInputStream
ObjectInputStream : Read object from stream.
PipedInputStream :
PushbackInputStream
SequenceInputStream :

  • OutputStream (OutputStreamWriter)

BufferedOutputStream
ByteArrayOutputStream
FileOutputStream
PrintStream : System.out
//seldom use
DataOutputStream
ObjectOutputStream
PipedOutputStream

通常用法

InputStream bin = null;
OutputStream bout = null;
byte[] buffer = new byte[1024];  //
int length;

try {
    bin = SomeInputStream();
    bout = SomeOutputStream();
   
    while((length = bin.read(buffer)) != -1) {
        bout.write(buffer, 0, length);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        bin.close();
        bout.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Reader & Writer

  • Reader

BufferedReader
CharArrayReader
FileReader
StringReader

 

//较少使用
PipedReader
PushbackReader

  • Writer

BufferedWriter
CharArrayWriter
FileWriter
PrintWriter
StringWriter

 

//少用
PipedWriter

 

一些说明:

PrintWriter & PrintStream 最大特点就是它们提供了格式化的功能。pw.format("%s world", "hello");

 

Commons IO

IOUtils

This class provides static utility methods for input/output operations.

  • closeQuietly - these methods close a stream ignoring nulls and exceptions
  • toXxx/read - these methods read data from a stream
  • write - these methods write data to a stream
  • copy - these methods copy all the data from one stream to another
  • contentEquals - these methods compare the content of two streams

FileUtils

 

  • writing to a file
  • reading from a file
  • make a directory including parent directories
  • copying files and directories
  • deleting files and directories
  • converting to and from a URL
  • listing files and directories by filter and extension
  • comparing file content
  • file last changed date
  • calculating a checksum

FilenameUtils

  • the prefix - C:\
  • the path - dev\project\
  • the full path - C:\dev\project\
  • the name - file.txt
  • the base name - file
  • the extension - txt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值