Java文件操作函数及文件IO流处理方法
Java提供了一系列的文件操作函数和文件IO流处理方法,用来对文件进行读写和操作。下面是一些常用的文件操作函数及文件IO流处理方法。
1. 文件操作函数:
- File类:Java提供了File类来表示文件和目录。可以通过File类的方法来创建、删除、重命名文件和目录,获取文件属性等。
- FileInputStream类:用于从文件中读取数据的输入流。可以使用它来读取文件的内容,并将内容存储到字节数组或缓冲区中。
- FileOutputStream类:用于向文件中写入数据的输出流。可以使用它来向文件中写入字节、字节数组或缓冲区的内容。
2. 文件IO流处理方法:
- 字节流处理方法:
- read()和write()方法:用于读取和写入单个字节。
- read(byte[] b)和write(byte[] b)方法:用于读取和写入字节数组。
- read(byte[] b, int off, int len)和write(byte[] b, int off, int len)方法:用于读取和写入指定长度的字节数组的一部分。
- 字符流处理方法:
- read()和write()方法:用于读取和写入单个字符。
- read(char[] c)和write(char[] c)方法:用于读取和写入字符数组。
- read(char[] c, int off, int len)和write(char[] c, int off, int len)方法:用于读取和写入指定长度的字符数组的一部分。
3. 文件操作示例:
- 创建文件夹:
File folder = new File("path/to/folder");
folder.mkdir();
- 创建文件:
File file = new File("path/to/file.txt");
file.createNewFile();
- 删除文件:
File file = new File("path/to/file.txt");
file.delete();
- 重命名文件:
File file = new File("path/to/oldfile.txt");
File newFile = new File("path/to/newfile.txt");
file.renameTo(newFile);
4. 文件IO流处理示例:
- 读取文件内容:
FileInputStream fis = new FileInputStream("path/to/file.txt");
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
// 处理读取到的数据
}
fis.close();
- 写入文件内容:
FileOutputStream fos = new FileOutputStream("path/to/file.txt");
String content = "Hello, World!";
byte[] buffer = content.getBytes();
fos.write(buffer);
fos.close();
无论是文件操作函数还是文件IO流处理方法,都需要在使用完成后关闭文件流,以释放资源。此外,还可以使用异常处理机制来处理文件操作和文件IO流处理中可能发生的异常。
