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

使用Java IO库中的函数读写文件

发布时间:2023-05-21 14:12:21

在Java中读写文件是很常见的任务,而Java IO库是用于处理输入输出的标准库。它包括了一组类和接口,用于处理不同类型的I/O操作。

常用的读文件函数有FileInputStream和BufferedReader。FileInputStream是一个简单的用于读取二进制文件的类。读取文本文件时,我们通常将其包装在BufferedReader中使用,BufferedReader提供了更方便的读取文本方法来读取文本文件。

举个例子:

File file = new File("example.txt");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));

String line;
while((line = br.readLine()) != null){
    System.out.println(line);
}

fis.close();
br.close();

上面的代码使用了FileInputStream和BufferedReader来读取文件example.txt的内容,并输出到控制台中。

此外,还有一些其他的文件读取方式。利用Scanner类可以轻松读取文本文件:

File file = new File("example.txt");
Scanner sc = new Scanner(file);

while(sc.hasNextLine()){
    System.out.println(sc.nextLine());
}

sc.close();

利用Files类也可以实现文件读取。Files类提供了很多静态方法来操作文件和目录。

Path path = Paths.get("example.txt");
List<String> lines = Files.readAllLines(path);
for(String line : lines){
    System.out.println(line);
}

除了读取文件,Java IO库还包括了很多写文件的函数。常用的写文件函数有FileOutputStream和BufferedWriter。与读取文件类似,FileOutputStream用于写二进制文件,而BufferedWriter则用于写文本文件并提供更方便的写入文本方法。

举个例子:

File file = new File("example.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

bw.write("This is an example.");
bw.newLine();
bw.write("This is another example.");

bw.close();
fos.close();

上面的代码使用了FileOutputStream和BufferedWriter来将一些字符串写入文件example.txt中。

此外,利用PrintWriter类也可以写文件:

File file = new File("example.txt");
PrintWriter pw = new PrintWriter(file);

pw.println("This is an example.");
pw.println("This is another example.");

pw.close();

利用Files类也可以实现文件写入。Files类提供了一个静态方法用于写入文本文件:

Path path = Paths.get("example.txt");
String content = "This is an example.
" +
                "This is another example.
";
Files.write(path, content.getBytes(), StandardOpenOption.CREATE);

上述代码中,我们将文件名作为一个字符串传递给Path构造函数来获取文件路径,然后将文件内容存储在一个字符串变量中,并将其转换为字节数组。最后,我们通过Files.write()方法将字节数组写入文件。

总之,Java IO库提供了各种读取和写入文件的函数和方法,可以根据需要选择最合适的方式进行文件操作。