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

Java中的文件处理函数:文件读写、复制、删除等

发布时间:2023-06-15 14:29:20

Java中的文件处理函数能够帮助开发者完成文件的读取、写入、复制和删除等操作。这些函数可以方便快捷地操作文件,提高开发效率。

1.文件读取

Java中的文件读取函数主要有FileInputStream和BufferedReader两种。

FileInputStream函数可以读取二进制文件,例如图片、音频及视频等。其用法为:

FileInputStream fis = new FileInputStream("file.txt");
int i;
while ((i = fis.read()) != -1) {
    System.out.println((char) i);
}
fis.close();

BufferedReader函数可以读取文本文件,例如txt和csv等。其用法为:

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}
br.close();

2.文件写入

Java中的文件写入函数主要有FileOutputStream和BufferedWriter两种。

FileOutputStream函数可以写入二进制文件,例如图片、音频及视频等。其用法为:

FileOutputStream fos = new FileOutputStream("file.txt");
String str = "Hello World";
byte[] bytes = str.getBytes();
fos.write(bytes);
fos.close();

BufferedWriter函数可以写入文本文件,例如txt和csv等。其用法为:

BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"));
bw.write("Hello World");
bw.newLine();
bw.close();

3.文件复制

Java中的文件复制函数主要有FileInputStream和FileOutputStream以及BufferedInputStream和BufferedOutputStream两种。

使用FileInputStream和FileOutputStream函数进行复制,其用法为:

FileInputStream fis = new FileInputStream("file.txt");
FileOutputStream fos = new FileOutputStream("copy.txt");
int len;
byte[] bytes = new byte[1024];
while ((len = fis.read(bytes)) != -1) {
    fos.write(bytes, 0, len);
}
fos.close();
fis.close();

使用BufferedInputStream和BufferedOutputStream函数进行复制,其用法为:

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("file.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.txt"));
int len;
byte[] bytes = new byte[1024];
while ((len = bis.read(bytes)) != -1) {
    bos.write(bytes, 0, len);
}
bos.close();
bis.close();

4.文件删除

Java中的文件删除函数主要有File类的delete()函数。

其用法为:

File file = new File("file.txt");
if (file.delete()) {
    System.out.println("文件删除成功!");
} else {
    System.out.println("文件删除失败!");
}

以上是Java中常用的文件处理函数,使用这些函数可以方便快捷地操作文件,提高开发效率。