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

Java函数中如何实现文件读写和操作

发布时间:2023-06-07 03:09:52

在Java函数中,可以使用FileInputStream和FileOutputStream来实现文件的读写操作,可以使用File和Path类来实现文件的操作(例如创建,删除,重命名等操作)。

以下是几个常见的文件读写和操作函数:

1. 读取文件内容

public static String readFile(String fileName) throws IOException {
    try (FileInputStream fis = new FileInputStream(fileName)) {
        int size = fis.available();
        byte[] buffer = new byte[size];
        fis.read(buffer);
        return new String(buffer);
    }
}

2. 写入文件内容

public static void writeFile(String fileName, String content) throws IOException {
    try (FileOutputStream fos = new FileOutputStream(fileName)) {
        fos.write(content.getBytes());
    }
}

3. 创建文件

public static void createFile(String fileName) throws IOException {
    File file = new File(fileName);
    if (!file.exists()) {
        file.createNewFile();
    }
}

4. 删除文件

public static void deleteFile(String fileName) throws IOException {
    File file = new File(fileName);
    if (file.exists()) {
        file.delete();
    }
}

5. 重命名文件

public static void renameFile(String oldFileName, String newFileName) throws IOException {
    File oldFile = new File(oldFileName);
    File newFile = new File(newFileName);
    if (oldFile.exists()) {
        oldFile.renameTo(newFile);
    }
}

以上是常见的文件读写和操作函数,也可以使用其他类库或框架来实现不同的需求。