Java中的文件IO操作方法
发布时间:2023-07-01 13:59:52
Java中的文件IO操作方法主要包括文件的读取和写入操作,下面将介绍一些常用的方法。
文件读取方法:
1. 使用File类读取文件信息:通过File类的构造方法可以创建一个文件对象,然后通过文件对象的一些方法来获取文件的信息,如文件名、文件路径等。
File file = new File("file.txt");
String fileName = file.getName(); // 获取文件名
String filePath = file.getAbsolutePath(); // 获取文件绝对路径
2. 使用FileReader类读取文本文件:FileReader类用于读取字符文件,可以通过该类的read()方法读取文件的内容,并将其保存到字符数组中。
File file = new File("file.txt");
char[] content = new char[1024]; // 创建一个字符数组用于保存文件内容
try (FileReader reader = new FileReader(file)) {
int len = reader.read(content); // 读取文件内容,并返回读取的字符数
String fileContent = new String(content, 0, len); // 将字符数组转换为字符串
} catch (IOException e) {
e.printStackTrace();
}
3. 使用BufferedReader类读取文本文件:BufferedReader类是一个字符缓冲流,可以通过其readLine()方法逐行读取文件内容。
File file = new File("file.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // 逐行输出文件内容
}
} catch (IOException e) {
e.printStackTrace();
}
文件写入方法:
1. 使用FileWriter类写入文本文件:FileWriter类用于写入字符文件,可以通过其write()方法将字符或字符数组写入文件中。
File file = new File("file.txt");
String content = "Hello, World!";
try (FileWriter writer = new FileWriter(file)) {
writer.write(content); // 将字符串写入文件
} catch (IOException e) {
e.printStackTrace();
}
2. 使用BufferedWriter类写入文本文件:BufferedWriter类是一个字符缓冲流,可以通过其write()方法将字符串写入文件中。
File file = new File("file.txt");
String content = "Hello, World!";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(content); // 将字符串写入文件
} catch (IOException e) {
e.printStackTrace();
}
3. 使用FileOutputStream类写入二进制文件:FileOutputStream类用于向文件中写入二进制数据,可以通过其write()方法将字节数组写入文件中。
File file = new File("file.txt");
byte[] data = {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21};
try (FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(data); // 将字节数组写入文件
} catch (IOException e) {
e.printStackTrace();
}
这些是Java中常用的文件IO操作方法,开发者可以根据具体需求选择适合的方法进行文件读取和写入操作。同时,还可以使用相应的输入流和输出流类,如InputStream、OutputStream等,以实现更加灵活和高效的文件IO操作。
