Java中的IO函数:输入输出流的常用方法,如何读写文件?
Java中的IO函数提供了许多用于输入输出的方法,包括字节流和字符流两种类型。
字节流:InputStream、OutputStream
1. InputStream常用方法:
- int read():读取下一个字节,返回一个整数,如果没有更多内容则返回-1。
- int read(byte[] b):读取一定数量的字节,并将其存储在缓冲区数组b中,返回读取的字节数。
- int available():返回可以从流中读取的字节数。
- void close():关闭输入流。
2. OutputStream常用方法:
- void write(int b):写入一个字节。
- void write(byte[] b):写入整个字节数组。
- void flush():将缓冲区中的数据刷新到底层流中。
- void close():关闭输出流。
字符流:Reader、Writer
1. Reader常用方法:
- int read():读取下一个字符,返回一个整数,如果没有更多内容则返回-1。
- int read(char[] cbuf):读取一定数量的字符,并将其存储在缓冲区数组cbuf中,返回读取的字符数。
- int read(char[] cbuf, int off, int len):读取最多len个字符,并将其存储在缓冲区cbuf中从偏移量off开始存储,返回读取的字符数。
- boolean ready():返回是否可以从读取器读取字符。
- void close():关闭读取器。
2. Writer常用方法:
- void write(int c):写入一个字符。
- void write(char[] cbuf):写入整个字符数组。
- void write(String str):写入字符串。
- void write(char[] cbuf, int off, int len):写入部分字符数组。
- void flush():将缓冲区中的数据刷新到底层流中。
- void close():关闭写入器。
如何读写文件?
1. 读取文件:
使用FileInputStream或FileReader创建一个输入流对象,然后使用输入流对象的read()方法逐个读取文件中的字节或字符,直到读完为止。最后,关闭输入流。
例如:
File file = new File("example.txt");
try(InputStream is = new FileInputStream(file)) {
byte[] content = new byte[(int) file.length()];
int length = is.read(content);
System.out.println(new String(content, 0, length));
} catch(IOException e) {
e.printStackTrace();
}
2. 写入文件:
使用FileOutputStream或FileWriter创建一个输出流对象,然后使用输出流对象的write()方法逐个写入字节或字符到文件中,最后,关闭输出流。
例如:
File file = new File("example.txt");
try(OutputStream os = new FileOutputStream(file)) {
String content = "Hello, World!";
byte[] bytes = content.getBytes();
os.write(bytes);
} catch(IOException e) {
e.printStackTrace();
}
以上就是在Java中使用IO函数进行读写文件的基本方法。要注意关闭输入输出流,避免资源泄漏。另外,为了提高效率,可以使用缓冲流来读写大文件,减少磁盘读写次数。
