ubuntu

Ubuntu Java如何处理文件I/O

小樊
39
2025-04-25 15:14:49
栏目: 编程语言

在Ubuntu上使用Java进行文件I/O操作,你可以使用Java标准库中的java.iojava.nio包。以下是一些基本的文件I/O操作示例:

  1. 读取文件内容:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 写入文件内容:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFile {
    public static void main(String[] args) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"));
            writer.write("Hello, World!");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 使用java.nio进行文件I/O操作:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class NIOFileOperations {
    public static void main(String[] args) {
        try {
            // 读取文件内容到List中
            List<String> lines = Files.readAllLines(Paths.get("example.txt"));
            for (String line : lines) {
                System.out.println(line);
            }

            // 写入内容到文件
            Files.write(Paths.get("example_output.txt"), "Hello, World!".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这些示例展示了如何在Ubuntu上使用Java进行基本的文件I/O操作。你可以根据自己的需求修改这些示例,以满足你的应用程序的需求。

0
看了该问题的人还看了