Java 中的文件操作函数及其使用方法介绍!
Java是一门广泛应用于跨平台应用的编程语言,而文件操作是Java应用程序中不可或缺的一部分。Java既提供了文件输入和输出流来进行文件的读写,也提供了文件处理类和文件IO流类,方便对文件进行处理。下面将介绍一些常用的文件操作函数及其使用方法。
1. File类
File类是java.io包中的一个类,它提供了访问文件和目录的方法。File类的主要方法有:
- exists():判断文件或目录是否存在
- isDirectory():判断是否是目录
- isFile():判断是否是文件
- getName():返回文件名或目录名
- getPath():返回文件或目录的路径名
- getParent():返回父目录的路径名
- mkdir():创建一个新的目录
- createNewFile():创建一个新的文件
下面是一个使用File类创建文件和目录的例子:
import java.io.*;
public class FileTest {
public static void main(String[] args) {
try {
// 创建一个新的文件
File file = new File("file.txt");
if(file.createNewFile()){
System.out.println("文件创建成功!");
}else{
System.out.println("文件已存在。");
}
// 创建一个新的目录
File dir = new File("dir");
if(dir.mkdir()){
System.out.println("目录创建成功!");
}else{
System.out.println("目录已存在。");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果:
文件创建成功! 目录创建成功!
2. FileInputStream类和FileOutputStream类
FileInputStream和FileOutputStream是java.io包中用于读写文件的类,它们用于将字节从文件读取到内存中或将字节从内存写入到文件中。
下面是一个使用FileInputStream和FileOutputStream读写文件的例子:
import java.io.*;
public class StreamTest {
public static void main(String[] args) {
try {
// 读取文件内容
File file = new File("file.txt");
FileInputStream fis = new FileInputStream(file);
byte[] content = new byte[(int) file.length()];
fis.read(content);
fis.close();
System.out.println(new String(content));
// 写入文件内容
FileOutputStream fos = new FileOutputStream(file);
String str = "Hello, world!";
fos.write(str.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果:
文件创建成功! Hello, world!
3. FileReader类和FileWriter类
FileReader和FileWriter类是java.io包中用于读写文件的类,与FileInputStream和FileOutputStream不同的是,它们使用字符流而不是字节流。除了读写文件外,它们还可以读写文本文件。
下面是一个使用FileReader和FileWriter读写文件的例子:
import java.io.*;
public class ReaderTest {
public static void main(String[] args) {
try {
// 读取文件内容
File file = new File("file.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String content = br.readLine();
fr.close();
br.close();
System.out.println(content);
// 写入文件内容
FileWriter fw = new FileWriter(file);
String str = "Hello, world!";
fw.write(str);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果:
文件创建成功! Hello, world!
4. RandomAccessFile类
RandomAccessFile类是java.io包中用于随机访问文件的类,它可以进行读、写、插入和删除等操作。相比于FileInputStream和FileOutputStream,RandomAccessFile类更加灵活且易于使用,但是也更复杂一些。
下面是一个使用RandomAccessFile访问文件的例子:
import java.io.*;
public class RandomAccessFileTest {
public static void main(String[] args) {
try {
// 写入文件内容
RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
String str = "Hello, world!";
raf.write(str.getBytes());
raf.close();
// 读取文件内容
raf = new RandomAccessFile("file.txt", "r");
raf.seek(2);
byte[] content = new byte[10];
raf.read(content);
raf.close();
System.out.println(new String(content));
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果:
文件创建成功! llo, worl
以上几个类是Java中常用的文件操作类,它们可以满足大部分文件操作的需求。除了以上的类之外,在Java中还有很多其他文件操作类和接口,例如ZipInputStream和ZipOutputStream等,有兴趣的读者可以自行了解。
