欢迎访问宙启技术站
智能推送

Java函数如何处理文件读写操作?

发布时间:2023-06-16 20:11:42

在Java中,可以使用标准库中的java.io包来处理文件读写操作。该包提供了几个类用于读取和写入数据到文件中,包括File,FileInputStream,FileOutputStream,BufferedReader和BufferedWriter等。下面对这些类进行简要描述:

1.File类

File类表示磁盘上的一个文件或目录,可以用来查询文件的信息和操作文件。常用的方法包括:

- exists()方法:检查文件是否存在

- isFile()方法:检查是否为文件

- isDirectory()方法:检查是否为目录

- getName()方法:返回文件名

- getParent()方法:返回父目录的路径

- getPath()方法:返回文件的绝对路径

示例代码:

File file = new File("test.txt");

if(file.exists()){

   System.out.println("File exists!");

}

2.FileInputStream类

FileInputStream 用于打开一个文件并读取数据,它继承自InputStream类,常用的方法包括:

- read()方法:读取一个字节

- read(byte[] b)方法:读取一定量的字节,将其存入缓冲区数组b中

- available()方法:返回还有多少可用的字节可以读取

- close()方法:关闭文件流

示例代码:

try (FileInputStream inFile = new FileInputStream("test.txt")) {

   int b;

   while ((b = inFile.read()) != -1) {

       System.out.print((char)b);

   }

} catch (IOException e) {

   System.err.println(e.getMessage());

}

3.FileOutputStream类

FileOutputStream类用于写入数据到文件中,它继承自OutputStream类,常用的方法包括:

- write(int b)方法:将一个字节写入文件

- write(byte[] b)方法:将缓冲区数组b中的字节写入文件

- flush()方法:将缓冲区的内容强制输出到文件中

- close()方法:关闭文件流

示例代码:

try (FileOutputStream outFile = new FileOutputStream("test.txt")) {

   String str = "Hello World!";

   outFile.write(str.getBytes());

} catch (IOException e) {

   System.err.println(e.getMessage());

}

4.BufferedReader和BufferedWriter类

BufferedReader和BufferedWriter类是用于高效读取和写入数据的带缓冲的字符流,它们读写字符数据时,会将字节转换成字符并以缓冲的方式进行读写。常用的方法包括:

- readLine()方法:读取一行文本

- newLine()方法:写入一个换行符

- write(String s)方法:将字符串写入文件

- close()方法:关闭文件流

示例代码:

try (BufferedReader br = new BufferedReader(new FileReader("test.txt"));

        BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {

   String line;

   while ((line = br.readLine()) != null) {

       bw.write(line);

       bw.newLine();

   }

} catch (IOException e) {

   System.err.println(e.getMessage());

}

总的来说,在Java中处理文件读写操作可以用以上几个类来实现,读写文件时应注意异常处理和及时关闭文件流以避免资源泄漏。